MySQLdb默认查询结果都是返回tuple,输出时候不是很方便,必须按照0,1这样读取,无意中在网上找到简单的修改方法,就是传递一个cursors.DictCursor就行。
默认程序:
import MySQLdb
db = MySQLdb.connect(host = 'localhost', user = 'root', passwd = '123456', db = 'test')
cursor = db.cursor()
cursor.execute('select * from user')
rs = cursor.fetchall()
print rs
# 返回类似如下
# ((1000L, 0L), (2000L, 0L), (3000L, 0L))
修改后:
import MySQLdb
import MySQLdb.cursors
db = MySQLdb.connect(host = 'localhost', user = 'root', passwd = '
123456
', db = 'test',cursorclass = MySQLdb.cursors.DictCursor)
cursor = db.cursor()
cursor.execute('select * from user')
rs = cursor.fetchall()
print rs
# 返回类似如下
# ({'age': 0L, 'num': 1000L}, {'age': 0L, 'num': 2000L}, {'age': 0L, 'num': 3000L})
或者也可以用下面替换connect和cursor部分
db = MySQLdb.connect(host = 'localhost', user = 'root', passwd = '123456', db = 'test')
cursor
=
conn
.
cursor
(
cursorclass
=
MySQLdb
.
cursors
.
DictCursor
)
python mysqldb 查询返回字典结构
最新推荐文章于 2024-09-13 09:26:07 发布
本文介绍了一种简单的方法来优化MySQL查询结果的展示形式,通过设置游标的类型为字典游标,可以将查询结果从元组形式转换为字典形式,便于后续的数据处理。
2576

被折叠的 条评论
为什么被折叠?



