网站建设哪家便,群晖 wordpress是什么,网站可以做哪些广告语,seo推广的方法MySQLdb默认查询结果都是返回tuple#xff0c;输出时候不是很方便#xff0c;必须按照0#xff0c;1这样读取#xff0c;无意中在网上找到简单的修改方法#xff0c;就是传递一个cursors.DictCursor就行。
默认程序#xff1a;
import MySQLdb
db MySQLdb.connect(ho…MySQLdb默认查询结果都是返回tuple输出时候不是很方便必须按照01这样读取无意中在网上找到简单的修改方法就是传递一个cursors.DictCursor就行。
默认程序
import MySQLdb
db MySQLdb.connect(hostlocalhost, userroot, passwd123456, dbtest)
cur db.cursor()
cur.execute(select * from user)
rs cur.fetchall()
print rs
# 返回类似如下
# ((1000L, 0L), (2000L, 0L), (3000L, 0L))修改后
import MySQLdb
import MySQLdb.cursors
db MySQLdb.connect(hostlocalhost, userroot, passwd123456, dbtest,cursorclassMySQLdb.cursors.DictCursor)
cur db.cursor()
cur.execute(select * from user)
rs cur.fetchall()
print rs
# 返回类似如下
# ({age: 0L, num: 1000L}, {age: 0L, num: 2000L}, {age: 0L, num: 3000L})或者也可以用下面替换connect和cursor部分
db MySQLdb.connect(hostlocalhost, userroot, passwd123456, dbtest)
cur db.cursor(cursorclassMySQLdb.cursors.DictCursor)我的实践
输出为元组类型
import pymysqldb pymysql.connect(localhost, root, 123456, filestore)
cursor db.cursor()
sqlselect * from tablelist where id%s %4
#查询方法一
cursor.execute(sql)
resultcursor.fetchall()
print(result,result)sql2select * from tablelist where id%s
values(4) # 此处为元组类型
#查询方法二
cursor.execute(sql2,values)
result2cursor.fetchall()
print(result2,result2)
id_list[]
tablename_list[]
tabletime_lsit[]
cursor.execute(select * from tablelist where id%s,[4,])
result3cursor.fetchall()
print(type(result3),type(result3))
#对((6, engineeringdata20180901, 1535731200),)类型数据的提取
for i in range(len(result3)):id_list.append(result3[i][0])tablename_list.append(result3[i][1])tabletime_lsit.append(result3[i][2])
print(id_list)
print(tabletime_lsit)
print(tablename_list)
cursor.close()
db.close()
#输出结果
result ((6, engineeringdata20180901, 1535731200), (618, engineeringdata20180904, 1535990400))
result2 ((6, engineeringdata20180901, 1535731200), (618, engineeringdata20180904, 1535990400))
type(result3) class tuple
[6, 618]
[1535731200, 1535990400]
[engineeringdata20180901, engineeringdata20180904]
输出为list类型
list_id[]
list_tablename[]
list_tabletime[]
listget_list(select * from tablelist where id%s,[4])
print(list:,list)
# 对[{id: 6, tablename: engineeringdata20180901, tabletime: 1535731200},]类型数据的提取
for i in range(len(list)):print(list[i])list_id.append(list[i][id])list_tablename.append(list[i][tablename])list_tabletime.append(list[i][tabletime])
print(list_id:,list_id)
print(list_tabletime:,list_tabletime)
print(list_tablename:,list_tablename)
# 输出结果为
list: [{id: 6, tablename: engineeringdata20180901, tabletime: 1535731200}, {id: 618, tablename: engineeringdata20180904, tabletime: 1535990400}]
{id: 6, tablename: engineeringdata20180901, tabletime: 1535731200}
{id: 618, tablename: engineeringdata20180904, tabletime: 1535990400}
list_id: [6, 618]
list_tabletime: [1535731200, 1535990400]
list_tablename: [engineeringdata20180901, engineeringdata20180904]