Python查询Mysql时返回字典结构的代码

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,(3000L,0L))
修改后:

import MysqLdb
import MysqLdb.cursors
db = MysqLdb.connect(host = ´localhost´,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},'num': 3000L}) 或者也可以用下面替换connect和cursor部分

db = MysqLdb.connect(host = ´localhost´,db = ´test´)
cursor = conn.cursor(cursorclass = MysqLdb.cursors.DictCursor)

相关文章

方案一 代码 在Python中,可以使用wave模块来读取双通道(立...
简介 一个用python实现的科学计算,包括: 1、一个强大的N维...
使用爬虫利器 Playwright,轻松爬取抖查查数据 我们先分析登...
轻松爬取灰豚数据的抖音商品数据 调用两次登录接口实现模拟登...
成功绕过阿里无痕验证码,一键爬取飞瓜数据 飞瓜数据的登录接...
一文教你从零开始入门蝉妈妈数据爬取,成功逆向破解数据加密...