Sqlite和Python – 使用fetchone()返回一个字典?
发布时间:2020-12-12 19:16:19 所属栏目:百科 来源:网络整理
导读:我在python 2.5中使用sqlite3。我创建了一个如下所示的表: create table votes ( bill text,senator_id text,vote text) 我正在用这样的方式访问它: v_cur.execute("select * from votes")row = v_cur.fetchone()bill = row[0]senator_id = row[1]vote = r
我在python 2.5中使用sqlite3。我创建了一个如下所示的表:
create table votes ( bill text,senator_id text,vote text) 我正在用这样的方式访问它: v_cur.execute("select * from votes") row = v_cur.fetchone() bill = row[0] senator_id = row[1] vote = row[2] 我想要做的是使用fetchone(或其他方法)返回字典而不是列表,以便我可以通过名称而不是位置来引用该字段。例如: bill = row['bill'] senator_id = row['senator_id'] vote = row['vote'] 我知道你可以用MySQL这样做,但有谁知道如何使用SQLite? 谢谢!!! 过去这样做的方式:def dict_factory(cursor,row): d = {} for idx,col in enumerate(cursor.description): d[col[0]] = row[idx] return d 然后在你的连接中设置它: from pysqlite2 import dbapi2 as sqlite conn = sqlite.connect(...) conn.row_factory = dict_factory 这在pysqlite-2.4.1和python 2.5.4下工作。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |