手机
当前位置:查字典教程网 >脚本专栏 >python >Python查询Mysql时返回字典结构的代码
Python查询Mysql时返回字典结构的代码
摘要:MySQLdb默认查询结果都是返回tuple,输出时候不是很方便,必须按照0,1这样读取,无意中在网上找到简单的修改方法,就是传递一个cur...

MySQLdb默认查询结果都是返回tuple,输出时候不是很方便,必须按照0,1这样读取,无意中在网上找到简单的修改方法,就是传递一个cursors.DictCursor就行。

默认程序:

MySQLdb默认查询结果都是返回tuple,输出时候不是很方便,必须按照0,1这样读取,无意中在网上找到简单的修改方法,就是传递一个cursors.DictCursor就行。默认程序:

复制代码 代码如下:

import MySQLdb

db = MySQLdb.connect(host = ´localhost´, user = ´root´, passwd = ´123456´, db = ´test´)

cursor = db.cursor()

cursor.execute(´select * from table´)

rs = cursor.fetchall()

print rs

# 返回类似如下

# ((1000L, 0L), (2000L, 0L), (3000L, 0L))

修改后:

复制代码 代码如下:

import MySQLdb

import MySQLdb.cursors

db = MySQLdb.connect(host = ´localhost´, user = ´root´, passwd = ´123456´, db = ´test´,cursorclass = MySQLdb.cursors.DictCursor)

cursor = db.cursor()

cursor.execute(´select * from table´)

rs = cursor.fetchall()

print rs

# 返回类似如下

# ({'age': 0L, 'num': 1000L}, {'age': 0L, 'num': 2000L}, {'age': 0L, 'num': 3000L}) 或者也可以用下面替换connect和cursor部分

复制代码 代码如下:

db = MySQLdb.connect(host = ´localhost´, user = ´root´, passwd = ´123456´, db = ´test´)

cursor = conn.cursor(cursorclass = MySQLdb.cursors.DictCursor)

【Python查询Mysql时返回字典结构的代码】相关文章:

python3.0 字典key排序

Python 文件操作实现代码

python中将阿拉伯数字转换成中文的实现代码

python 域名分析工具实现代码

python实现bitmap数据结构详解

python 图片验证码代码分享

Python 返回汉字的汉语拼音

Python 初始化多维数组代码

python不带重复的全排列代码

python和pyqt实现360的CLable控件

精品推荐
分类导航