返回 Python ...... 登陆

Python Sqlite3以字典形式返回查询结果的实现方法

巴扎黑 2017-01-09 17:02:50 348

sqlite3本身并没有像pymysql一样原生提供字典形式的游标。

cursor = conn.cursor(pymysql.cursors.DictCursor)

但官方文档里已经有预留了相应的实现方案。

def dict_factory(cursor, row):
  d = {}
  for idx, col in enumerate(cursor.description):
    d[col[0]] = row[idx]
  return d

使用这个函数代替conn.raw_factory属性即可。

con = sqlite3.connect(":memory:") #打开在内存里的数据库
con.row_factory = dict_factory
cur = con.cursor()
cur.execute("SELECT 1 as a")
print cur.fetchone()["a"]

更多关于Python Sqlite3以字典形式返回查询结果的实现方法请关注PHP中文网(www.php.cn)其他文章!   


最新手记推荐

• 用composer安装thinkphp框架的步骤 • 省市区接口说明 • 用thinkphp,后台新增栏目 • 管理员添加编辑删除 • 管理员添加编辑删除

全部回复(0)我要回复

暂无评论~
  • 取消 回复 发送
  • PHP中文网