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

yipeiwu_com5年前Python基础
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一行输出不显示的问题

在使用python函数print()时,如下代码会出现输出无法显示的问题: 分三次在一行输出 123 print(1, end="") print(2, end="") print(...

如何基于pythonnet调用halcon脚本

如何基于pythonnet调用halcon脚本

这篇文章主要介绍了如何基于pythonnet调用halcon脚本,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 最近的项目中遇到了使用...

python 构造三维全零数组的方法

如下所示: temp1 = [[] for i in range(10)] temp2 = [temp1 for i in range(20)] temp3 = [temp2 for...

python函数不定长参数使用方法解析

这篇文章主要介绍了python函数不定长参数使用方法解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 pathon中的函数可以使用不...

Python图片的横坐标汉字实例

给一个例子 : # -*- coding: utf-8 -*- import matplotlib.pyplot as plt  import py_hanzi as ch&...