Python:如何使用mysqldb将MySQL表导入字典?
有人知道我怎么用mysqldb把一个有很多行的MySQL表格变成Python中的字典对象列表吗?
我的意思是把一组MySQL的行,里面有'a'、'b'和'c'这些列,转换成一个看起来像这样的Python对象:
data = [ { 'a':'A', 'b':(2, 4), 'c':3.0 }, { 'a':'Q', 'b':(1, 4), 'c':5.0 }, { 'a':'T', 'b':(2, 8), 'c':6.1 } ]
谢谢 :)
5 个回答
7
我觉得用 mysql.connector 把查询结果转换成字典比用 MySQLdb 要简单得多,而且支持的 Python 版本也更多:
cursor = conn.cursor(dictionary=True)
下面是一个详细的例子:
import mysql.connector # pip install mysql-connector-python
conn = mysql.connector.connect(host="localhost", user="user", passwd="pass", database="dbname")
cursor = conn.cursor(dictionary=True)
sql = "SELECT * FROM `table` WHERE 1"
cursor.execute(sql)
rows = cursor.fetchall()
for row in rows:
row["col"]
24
如果你需要使用多个游标,但只有一个需要是 MySQLdb.cursors.DictCursor,你可以这样做:
import MySQLdb
db = MySQLdb.connect(host='...', db='...', user='...t', passwd='...')
list_cursor = db.cursor()
dict_cursor = db.cursor(MySQLdb.cursors.DictCursor)
76
MySQLdb有一个专门的游标类,叫做DictCursor。你可以在连接数据库的时候,把想用的游标类传给MySQLdb.connect()这个函数。
import MySQLdb.cursors
MySQLdb.connect(host='...', cursorclass=MySQLdb.cursors.DictCursor)