您的位置:首页 > 编程语言 > Python开发

Python中让MySQL查询结果返回字典类型的方法

2018-04-11 07:06 801 查看
Python的MySQLdb模块是Python连接MySQL的一个模块,默认查询结果返回是tuple类型,只能通过0,1..等索引下标访问数据为tuple类型。

我们可以这么干使得数据查询结果返回字典类型,即 字段=数据
导入模块

import MySQLdb.cursors

完整代码:

import MySQLdb

import MySQLdb.cursors

class mydb(object):
def __init__(self, host,name,pw,dbname):
try:
#cursorclass = MySQLdb.cursors.DictCursor  返回的数据是字典类型 而不是元祖
self.conn = MySQLdb.connect(host,name,pw,dbname,charset='utf8',cursorclass = MySQLdb.cursors.DictCursor)
except MySQLdb,e:
print e
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: