Python - mysqlDB,sqlite结果作为字典
当我做一些像这样的事情
sqlite.cursor.execute("SELECT * FROM foo")
result = sqlite.cursor.fetchone()
我觉得我得记住列出现的顺序,才能把它们提取出来,比如说
result[0] is id
result[1] is first_name
有没有办法返回一个字典?这样我就可以直接用 result['id'] 或类似的方式来获取数据?
使用数字列的问题是,如果你写完代码后又插入了一列,可能就得修改代码,比如说原本 result[1] 是 first_name,现在可能变成了 date_joined,那就得更新所有相关的代码...
5 个回答
13
在mysqlDB中,你只需要在连接函数的调用中添加以下内容
cursorclass = MySQLdb.cursors.DictCursor
35
在编程中,有时候我们需要处理一些数据,比如从一个地方获取数据,然后在另一个地方使用这些数据。这个过程就像是把水从一个水桶倒到另一个水桶里。我们需要确保水不会洒出来,也就是确保数据在转移过程中不会丢失或出错。
为了做到这一点,我们可以使用一些工具和方法来帮助我们管理这些数据。比如,我们可以使用变量来存储数据,就像用一个瓶子装水一样。然后,我们可以在需要的时候随时取出这些数据,进行计算或显示。
此外,有时候我们还需要对数据进行一些处理,比如筛选出我们需要的部分,或者对数据进行排序。这就像是在水桶里挑选出干净的水,或者把水按顺序放好,以便更方便地使用。
总之,处理数据就像是管理水资源一样,我们需要小心翼翼,确保每一步都能顺利进行,这样才能得到我们想要的结果。
import MySQLdb
dbConn = MySQLdb.connect(host='xyz', user='xyz', passwd='xyz', db='xyz')
dictCursor = dbConn.cursor(MySQLdb.cursors.DictCursor)
dictCursor.execute("SELECT a,b,c FROM table_xyz")
resultSet = dictCursor.fetchall()
for row in resultSet:
print row['a']
dictCursor.close
dbConn.close()
5
David Beazley在他的《Python基础参考书》中有一个很好的例子。
我手头没有这本书,但我记得他的例子大概是这样的:
def dict_gen(curs):
''' From Python Essential Reference by David Beazley
'''
import itertools
field_names = [d[0].lower() for d in curs.description]
while True:
rows = curs.fetchmany()
if not rows: return
for row in rows:
yield dict(itertools.izip(field_names, row))
示例用法:
>>> import sqlite3
>>> conn = sqlite3.connect(':memory:')
>>> c = conn.cursor()
>>> c.execute('create table test (col1,col2)')
<sqlite3.Cursor object at 0x011A96A0>
>>> c.execute("insert into test values (1,'foo')")
<sqlite3.Cursor object at 0x011A96A0>
>>> c.execute("insert into test values (2,'bar')")
<sqlite3.Cursor object at 0x011A96A0>
# `dict_gen` function code here
>>> [r for r in dict_gen(c.execute('select * from test'))]
[{'col2': u'foo', 'col1': 1}, {'col2': u'bar', 'col1': 2}]