Python Sqlite3以字典形式返回查询结果的实现方法
时间:2021-01-18 14:43:42|栏目:Python代码|点击: 次
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编程在flask中模拟进行Restful的CRUD操作
栏 目:Python代码
下一篇:Pycharm中安装Pygal并使用Pygal模拟掷骰子(推荐)
本文标题:Python Sqlite3以字典形式返回查询结果的实现方法
本文地址:http://www.codeinn.net/misctech/46890.html






