Python:使用mysqldb将MySQL表导入为字典?

AP2*_*257 32 python mysql dictionary

任何人都知道如何使用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 } ]
Run Code Online (Sandbox Code Playgroud)

谢谢 :)

Tho*_*ers 70

MySQLdb有一个单独的游标类,DictCursor.您可以将要使用的游标类传递给MySQLdb.connect():

import MySQLdb.cursors
MySQLdb.connect(host='...', cursorclass=MySQLdb.cursors.DictCursor)
Run Code Online (Sandbox Code Playgroud)

  • 对于其他人阅读,你还需要在`import MySQLdb.cursors`之后的某处添加`MySQLdb.connect(host ='...',cursorclass = MySQLdb.cursors.DictCursor)`,以使代码段工作.(对不起,我无法抗拒!:D) (20认同)
  • 您一定错过了我实际上在代码片段中包含MySQL.cursors导入的事实. (4认同)
  • 完美,谢谢!对于其他人阅读,您还需要在Python脚本的顶部添加"import MySQLdb.cursors"以包含它. (3认同)

blu*_*Cat 22

如果你需要使用更多的游标,只需要一个是MySQLdb.cursors.DictCursor,你可以这样做:

import MySQLdb
db = MySQLdb.connect(host='...', db='...', user='...t', passwd='...')

list_cursor = db.cursor()
dict_cursor = db.cursor(MySQLdb.cursors.DictCursor)
Run Code Online (Sandbox Code Playgroud)


DaW*_*aWe 7

我认为使用mysql.connector将 select 转换为 dict 比 MySQLdb 更容易,并且支持更多 Python 版本:

cursor = conn.cursor(dictionary=True)
Run Code Online (Sandbox Code Playgroud)

详细示例:

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"]
Run Code Online (Sandbox Code Playgroud)