Python查询Mysql, sqlite时返回字典结构的代码(转)

来源:
https://blog.csdn.net/zhaihaifei/article/details/53898260

问题起源:
最近把MySQLdb.connect()换成了PooledDB(),select 之后,返回结构list 变成了dict,数据结构变了,要炸锅了。
解决方案:
PooledDB()连接的时候,多加了个参数:cursorclass = MySQLdb.cursors.DictCursor
去掉就好了

下面是转载内容:
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 table´)
rs = cursor.fetchall()
print rs

返回类似如下
((1000L, 0L), (2000L, 0L), (3000L, 0L))

加上cursorclass = MySQLdb.cursors.DictCursor

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 table´)
rs = cursor.fetchall()
print rs
返回类似如下
({‘age’: 0L, ‘num’: 1000L}, {‘age’: 0L, ‘num’: 2000L}, {‘age’: 0L, ‘num’: 3000L})

你可能感兴趣的:(Python查询Mysql, sqlite时返回字典结构的代码(转))