Python中让MySQL查询结果返回字典类型的方法,java返回类型

来源:未知 浏览 131次 时间 2021-06-13 04:22

Python的MySQLdb模块是Python连接MySQL的一个模块默认查询结果返回是tuple类型只能通过0,1..等索引下标访问数据
默认连接数据库:
代码如下:
MySQLdb.connect(
host=host,
user=user,
passwd=passwd,
db=db,
port=port,
charset=’utf8′
)
查询数据:
代码如下:
cur = conn.cursor()
cur.execute(‘select b_id from blog limit 1’)
data = cur.fetchall()
cur.close()
conn.close()

打印:
代码如下:
for row in data:
print type(row)
print row

Python中让MySQL查询结果返回字典类型的方法

为tuple类型。
我们可以这么干使得数据查询结果返回字典类型网站优化只能通过0,1..等索引下标访问数据
默认连接数据库:
代码如下:
MySQLdb.connect(
host=host,
user=user,
passwd=passwd,
db=db,
port=port,
charset=’utf8′
)
查询数据:
代码如下:
cur = conn.cursor()
cur.execute(‘select b_id from blog limit 1’)
data = cur.fetchall()
cur.close()
conn.close()

打印:
代码如下:
for row in data:
print type(row)
print row

Python中让MySQL查询结果返回字典类型的方法

为tuple类型。
我们可以这么干使得数据查询结果返回字典类型即 字段=数据
导入模块
代码如下:
import MySQLdb.cursors
在连接函数里加上这个参数 cursorclass = MySQLdb.cursors.DictCursor 如:
代码如下:
MySQLdb.connect(
host=host,
user=user,
passwd=passwd,
db=db,
port=port,
charset=’utf8′,
cursorclass = MySQLdb.cursors.DictCursor
)
再重新运行脚本看看执行结果:
代码如下:
type ‘dict’
{‘b_id’: 1L}

标签: port如下连接代码