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

Output:

<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如果要指定则值必须是整型,否则会出错!

分享

TITLE: Python设定MySQL结果集返回字典格式

LINK: https://www.qttc.net/319-python-query-mysql-return-dict-mode.html

NOTE: 原创内容,转载请注明出自琼台博客