python mysqldb 查询返回字典结构
2012-06-05 14:20
579 查看
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 user')
rs = cursor.fetchall()
print rs
# 返回类似如下
# ((1000L, 0L), (2000L, 0L), (3000L, 0L))[/i]
修改后:
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 user')
rs = cursor.fetchall()
print rs
# 返回类似如下
# ({'age': 0L, 'num': 1000L}, {'age': 0L, 'num': 2000L}, {'age': 0L, 'num': 3000L})[/i]
或者也可以用下面替换connect和cursor部分
db = MySQLdb.connect(host = 'localhost', user = 'root', passwd = '123456', db = 'test')
cursor = conn.cursor(cursorclass = MySQLdb.cursors.DictCursor)
默认程序:
import MySQLdb
db = MySQLdb.connect(host = 'localhost', user = 'root', passwd = '123456', db = 'test')
cursor = db.cursor()
cursor.execute('select * from user')
rs = cursor.fetchall()
print rs
# 返回类似如下
# ((1000L, 0L), (2000L, 0L), (3000L, 0L))[/i]
修改后:
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 user')
rs = cursor.fetchall()
print rs
# 返回类似如下
# ({'age': 0L, 'num': 1000L}, {'age': 0L, 'num': 2000L}, {'age': 0L, 'num': 3000L})[/i]
或者也可以用下面替换connect和cursor部分
db = MySQLdb.connect(host = 'localhost', user = 'root', passwd = '123456', db = 'test')
cursor = conn.cursor(cursorclass = MySQLdb.cursors.DictCursor)
相关文章推荐
- Python MySQLdb 查询返回字典结构
- python mysqldb 查询返回字典结构
- python mysqldb 查询返回字典结构
- Python查询Mysql, sqlite时返回字典结构的代码
- Python查询Mysql时返回字典结构的代码
- python mysql 查询返回字典结构
- Python查询Mysql时返回字典结构的代码
- Python查询Mysql时返回字典结构的代码
- Python查询Mysql, sqlite时返回字典结构的代码
- Python查询Mysql, sqlite时返回字典结构的代码
- Python查询Mysql时返回字典结构的代码
- Python中让MySQL查询结果返回字典类型的方法
- 让python的mysqldb返回的结果集为字典类型
- Python Sqlite3以字典形式返回查询结果的实现方法
- Python中让MySQL查询结果返回字典类型的方法
- python连接mysql查询数据返回字典格式
- 用python操作mysql数据库(之数据查询结果返回字典类型)
- Python中让MySQL查询结果返回字典类型的方法
- Python MySQLdb 查询返回字典结构
- Python中让MySQL查询结果返回字典类型的方法