mysqldb預設查詢結果都是返回tuple,輸出時候不是很方便,必須按照0,1這樣讀取,無意中在網上找到簡單的修改方法,就是傳遞乙個cursors.dictcursor就行。
預設程式:
import mysqldb
db = mysqldb.connect(host='localhost', user='root', passwd='123456', db='test')
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(host='localhost', user='root', passwd='123456', db='test',
cursorclass=mysqldb.cursors.dictcursor)
cur = db.cursor()
cur.execute('select * from user')
rs = cur.fetchall()
print rs
# 返回類似如下
# (, , )
或者也可以用下面替換connect和cursor部分
db = mysqldb.connect(host='localhost', user='root', passwd='123456', db='test')
cur = db.cursor(cursorclass=mysqldb.cursors.dictcursor)
我的實踐:
輸出為元組型別:
import pymysql
db = pymysql.connect("localhost", "root", "123456", "filestore")
cursor = db.cursor()
sql='select * from tablelist where id>%s' %4
#查詢方法一
cursor.execute(sql)
result=cursor.fetchall()
print('result',result)
sql2='select * from tablelist where id>%s'
values=('4') # 此處為元組型別
#查詢方法二
cursor.execute(sql2,values)
result2=cursor.fetchall()
print('result2',result2)
id_list=
tablename_list=
tabletime_lsit=
cursor.execute('select * from tablelist where id>%s',[4,])
result3=cursor.fetchall()
print('type(result3)',type(result3))
#對((6, 'engineeringdata20180901', '1535731200'),)型別資料的提取
for i in range(len(result3)):
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) [6, 618]
['1535731200', '1535990400']
['engineeringdata20180901', 'engineeringdata20180904']
輸出為list型別:
list_id=
list_tablename=
list_tabletime=
list=get_list('select * from tablelist where id>%s',[4])
print('list:',list)
# 對[,]型別資料的提取
for i in range(len(list)):
print(list[i])
print('list_id:',list_id)
print('list_tabletime:',list_tabletime)
print('list_tablename:',list_tablename)
# 輸出結果為:
list: [, ]
list_id: [6, 618]
list_tabletime: ['1535731200', '1535990400']
list_tablename: ['engineeringdata20180901', 'engineeringdata20180904']
python 使用sql查詢資料庫返回空集判斷
python中連線資料庫後,發出查詢語句而後逐條處理,標準語句如下 db pymysql.connect localhost 使用者名稱 口令 資料庫 charset utf8 cursor db.cursor cursor.execute sqlt results cursor.fetchall ...
Python 處理資料庫返回結果
游標執行後返回的結果都只是資料,但是不帶有列名標識。這裡需要處理2個問題 解決上面的2個問題,在python裡面可以採用下面的2種方式來處理。使用namedtuple 和 map object。使用yield 和 zip。下面是示例 result from db mysql 資料庫 import m...
python多執行緒查詢資料庫並獲取返回結果
pip install dbutils 1.3 pip install mysqlclient 2.0.1 import time import threading import mysqldb import queue from mysqldb.cursors import dictcursor ...