如何在python中以列名作为字典存储sql查询的结果?

时间:2016-12-06 01:18:10

标签: python sql dictionary

假设我有一个如下所示的查询,它只返回 单行

SELECT name, age, height, weight
FROM my_bio

我想将此查询的结果存储为如下字典:

SQLdict = {'name': 'eric', 'age': 27, 'height': '5.9', 'weight': '99'}

如何做到这一点?

1 个答案:

答案 0 :(得分:0)

使用MySQLdb.cursors.DictCursor获取结果为dict:

import MySQLdb
import MySQLdb.cursors

database = MySQLdb.connect(host = "localhost", user = "user", 
                           passwd = "password", db = "mydb",
                           cursorclass=MySQLdb.cursors.DictCursor)
c = database.cursor()

c.execute("SELECT name, age, height, weight FROM my_bio")
row = c.fetchone()

print row['name']