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

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,
        charset='utf8',
    cursorclass = MysqLdb.cursors.DictCursor
)

再重新运行脚本,看看执行结果:

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

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

相关文章

在前一篇博客中我们介绍了加侧旋的乒乓球弧圈技术的模拟,本...
在近期conda的版本更新中,有可能会删除路径下的_sysconfigd...
本文主要展示了一些lambda表达式的使用示例,通过这些示例,...
本文通过对比Jax和Numpy计算Normalized Hamming Distance的过...
我们知道GPU加速在可并行化程度比较高的算法中,能够发挥出比...
Numpy这个库在Python编程中非常的常用,不仅在性能上补足了P...