我在python 2.5中使用sqlite3。我创建了一个如下所示的表:
@H_301_18@
过去这样做的方式:
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下工作。