当前位置:首页 > 数据库 > SQlite

PythonSqlite3以字典形式返回查询结果方法介绍

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属性即可。

def dict_factory(cursor, row):  
    d = {}  
    for idx, col in enumerate(cursor.description):  
        d[col[0]] = row[idx]  
    return d  con = sqlite3.connect(":memory:") #打开在内存里的数据库
con.row_factory = dict_factory
cur = con.cursor()
cur.execute("select 1 as a")
print cur.fetchone()["a"]

以上就是Python Sqlite3以字典形式返回查询结果方法介绍的详细内容,更多请关注Gxl网其它相关文章!


【说明】本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!