python3 pymysql查询结果包含字段名

CloudXli 2020-06-04

python2使用MySQLdb模块进行连接mysql数据库进行操作;python3则使用pymysql模块进行连接mysql数据库进行操作;两者在语法上有稍微的差别,其中就包括查询结果包含字段名,具体例子如下:

python2:

import MySQLdb

conn = MySQLdb.connect(host=‘127.0.0.1‘,user=‘root‘,passwd=‘root‘,db=‘adu‘)
cur = conn.cursor(cursorclass=MySQLdb.cursors.DictCursor)

sql = ‘select * from test1‘
reCount = cur.execute(sql)
nRet = cur.fetchall()

cur.close()
conn.close()

print(nRet)
print(reCount)

pytnon3:

import pymysql

conn = pymysql.connect(host=‘127.0.0.1‘,user=‘root‘,passwd=‘root‘,db=‘adu‘)
cur = conn.cursor(cursor=pymysql.cursors.DictCursor)

sql = ‘select * from test1‘
reCount = cur.execute(sql)
nRet = cur.fetchall()

cur.close()
conn.close()

print(nRet)
print(reCount)

相关推荐