假设我有一个如下所示的查询,它只返回 单行 :
SELECT name, age, height, weight
FROM my_bio
我想将此查询的结果存储为如下字典:
SQLdict = {'name': 'eric', 'age': 27, 'height': '5.9', 'weight': '99'}
如何做到这一点?
答案 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']