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

yipeiwu_com6年前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实现宿舍管理系统

Python综合应用——宿舍管理系统,供大家参考,具体内容如下/p> 通过对 python 的函数,变量的应用,编写简单的关系系统 实现功能: 1.新增学生 2.显示全部学生信息...

Python使用Flask框架获取当前查询参数的方法

本文实例讲述了Python使用Flask框架获取当前查询参数的方法。分享给大家供大家参考。具体如下: 这段代码实现Python的Flask框架下获取当前查询参数,即QueryString...

Python中list初始化方法示例

本文实例讲述了Python中list初始化方法。分享给大家供大家参考,具体如下: 1、基本方法。 lst = [1, 2, 3, 4, 5] 2、初始化连续数字。 >...

python 打印出所有的对象/模块的属性(实例代码)

实例如下: import sys def print_all(module_): modulelist = dir(module_) length = len(module...

python使用KNN算法手写体识别

本文实例为大家分享了用KNN算法手写体识别的具体代码,供大家参考,具体内容如下 #!/usr/bin/python #coding:utf-8 import numpy as...