Python MySQLdb 库, 查询结果返回的是tuple, 输出的时候不是很方便, 因为只能通过索引读取内容, 查找了下, 可以通过指定 MySQLdb.cursors.DictCursor 返回 dict 内容数据.

默认情况下, 调用过程和返回结果:

import MySQLdb
db  = MySQLdb.connect(host='localhost', user='root', passwd='admin', db='test')
cur = db.cursor()
cur.execute('select * from user')
rs = cur.fetchall()
print rs
# 返回类似如下
# ((1000L, 0L), (2000L, 0L), (3000L, 0L))

使用 MySQLdb.cursors.DictCursor 之后返回的是 dict 结构, 看起来聚方便多了, 可读性也好:

import MySQLdb
import MySQLdb.cursors
db = MySQLdb.connect(host='localhost', user='root', passwd='admin', db='test',
                     cursorclass=MySQLdb.cursors.DictCursor)
cur = db.cursor()
cur.execute('select * from user')
rs = cur.fetchall()
print rs
# 返回类似如下
# ({'age': 0L, 'num': 1000L}, {'age': 0L, 'num': 2000L}, {'age': 0L, 'num': 3000L})

MySQLdb.cursors.DictCursor 参数的指定, 也可以在 cursor 获取的地方再指定:

db  = MySQLdb.connect(host='localhost', user='root', passwd='admin', db='test')
cur = db.cursor(cursorclass=MySQLdb.cursors.DictCursor)

【腾讯云】境外1核2G服务器低至2折,半价续费券限量免费领取!
https://cloud.tencent.com/act/cps/redirect?redirect=1068&cps_key=e4b50f6c64a4480367f8a8d16fd07c5a&from=console

标签: Python MySQLdb, DictCursor

添加新评论