当前位置: 移动技术网 > IT编程>脚本编程>Python > Python中让MySQL查询结果返回字典类型的方法

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

2019年03月27日  | 移动技术网IT编程  | 我要评论

六道禁典,连江在线,我的老婆是学生会长无修版

python的mysqldb模块是python连接mysql的一个模块,默认查询结果返回是tuple类型,只能通过0,1..等索引下标访问数据
默认连接数据库:

复制代码 代码如下:

mysqldb.connect(
    host=host,
        user=user,
        passwd=passwd,
        db=db,
        port=port,
        charset='utf8'
)

查询数据:
复制代码 代码如下:

cur = conn.cursor()
cur.execute('select b_id from blog limit 1')
data = cur.fetchall() 
cur.close()
conn.close()

打印:
复制代码 代码如下:

for row in data:
    print type(row)
    print row

执行结果:
复制代码 代码如下:

<type 'tuple'>
(1l,)

为tuple类型。
我们可以这么干使得数据查询结果返回字典类型,即 字段=数据
导入模块
复制代码 代码如下:

import mysqldb.cursors

在连接函数里加上这个参数  cursorclass = mysqldb.cursors.dictcursor 如:
复制代码 代码如下:

mysqldb.connect(
    host=host,
        user=user,
        passwd=passwd,
        db=db,
        port=port,
        charset='utf8',
    cursorclass = mysqldb.cursors.dictcursor
)

再重新运行脚本,看看执行结果:
复制代码 代码如下:

<type 'dict'>
{'b_id': 1l}

搞定!
注意,在连接的时候port如果要指定则值必须是整型,否则会出错!

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网