本文介绍了Sqlite和Python - 使用fetchone()返回一个字典?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在python 2.5中使用sqlite3。我创建了一个表格,如下所示:

 创建表格投票(
bill text,
senator_id文本,
投票文本)



我使用类似这样: / p>

  v_cur.execute(select * from votes)
row = v_cur.fetchone()
= row [0]
senator_id = row [1]
vote = row [2]


$ b b

我想要做的是有fetchone(或一些其他方法)返回一个字典,而不是一个列表,以便我可以通过名称而不是位置引用字段。例如:

  bill = row ['bill'] 
senator_id = row ['senator_id']
vote = row ['vote']



我知道你可以用MySQL做,

解决方案


我以前这样做:

  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下工作。


I'm using sqlite3 in python 2.5. I've created a table that looks like this:

   create table votes (
      bill text,
      senator_id text,
      vote text)

I'm accessing it with something like this:

v_cur.execute("select * from votes")
row = v_cur.fetchone()
bill = row[0]
senator_id = row[1]
vote = row[2]

What I'd like to be able to do is have fetchone (or some other method) return a dictionary, rather than a list, so that I can refer to the field by name rather than position. For example:

bill = row['bill']
senator_id = row['senator_id']
vote = row['vote']

I know you can do this with MySQL, but does anyone know how to do it with SQLite?

Thanks!!!

解决方案

The way I've done this in the past:

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

Then you set it up in your connection:

from pysqlite2 import dbapi2 as sqlite
conn = sqlite.connect(...)
conn.row_factory = dict_factory

This works under pysqlite-2.4.1 and python 2.5.4.

这篇关于Sqlite和Python - 使用fetchone()返回一个字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 10:00