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

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

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

  2021-03-19 我要评论
想了解Python查询Mysql时返回字典结构的代码的相关内容吗,在本文为您仔细讲解字典结构的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:字典结构,下面大家一起来学习吧。
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)

猜您喜欢

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们