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('selectb_idfrombloglimit1')
data=cur.fetchall()
cur.close()
conn.close()
打印:
forrowindata: printtype(row) printrow
执行结果:
<type'tuple'> (1L,)
为tuple类型。
我们可以这么干使得数据查询结果返回字典类型,即字段=数据
导入模块
importMySQLdb.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如果要指定则值必须是整型,否则会出错!
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下