开发者

Python, MySQL and SELECT output to dictionary with column names for keys

开发者 https://www.devze.com 2023-04-01 00:47 出处:网络
I have a MySQL table on which I\'m executing SELECT statements within Python. Is there anything out of the Python MySQLdb API that will, via the cursor, outp开发者_Go百科ut an array of dictionaries w

I have a MySQL table on which I'm executing SELECT statements within Python.

Is there anything out of the Python MySQLdb API that will, via the cursor, outp开发者_Go百科ut an array of dictionaries whose keys are the column names (and values are those in the returned rows)?


For me, this worked:

cursor = conn.cursor(dictionary=True)

Detailed example:

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"]


Please use dictionary cursor:

cursor = conn.cursor (MySQLdb.cursors.DictCursor)
0

精彩评论

暂无评论...
验证码 换一张
取 消