简体   繁体   中英

How to store results of sql query with column name as dictionary in python?

Suppose I have a query such as the following which returns only a single row :

SELECT name, age, height, weight
FROM my_bio

I want to store the result of this query as a dictionary like the following:

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

How can this be done?

Use MySQLdb.cursors.DictCursor for getting the result as 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']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM