pymysql之cur.fetchall() 和cur.fetchone()用法詳解
我就廢話不多說了,大家還是直接看程式碼吧!
import pymysql,hashlib 結果:單條結果 {'id': 1,'name': '打車','phone': '132453'} sql = 'select * from zxj' def op_mysql(sql,many=True): db_info = {'user': 'jxz','password': '123456','host': '118*******','db': 'jxz','port': 3306,'charset': 'utf8','autocommit': True} conn = pymysql.connect(**db_info) # 建立連線 cur = conn.cursor(pymysql.cursors.DictCursor) # 遊標 cur.execute(sql) # 執行sql語句,insert 、update 、delete if many: result = cur.fetchall() print('多條',result) else: result = cur.fetchone() # {''} print('dantiao',result) cur.close() conn.close() return result op_mysql(sql,many=False) # 傳入sql,預設為true ================================= md5加鹽2 def md5(s,salt="pymysql之cur.fetchall() 和cur.fetchone()用法詳解"): new_s = str(s) + salt m = hashlib.md5(new_s.encode()) return m.hexdigest()```
補充知識:python pymssql使用時,使用fetchone獲取的值怎麼在while裡操作多條資料
專案描述:
想把status狀態為1的資料查出來然後再通過while 遍歷update 資料,為了清楚測試時候的資料。
剛開始的程式碼是這樣的。
#coding:utf-8 import pymssql def connect(): connect=pymssql.connect((‘x.x.x.x'),‘x',‘x') cursor = connect.cursor() # 建立遊標 sql001='select *from xxxxx where xxxxx=273and Status=1 order by sysno desc'#查詢語句 cursor.execute(sql001) row=cursor.fetchone()#讀取查詢結果 print(row) if row==None: print("沒有查到資料") else: while row: print("sysno=%s" % (row[0])) cursor.execute("update xxxxx set Status=-1 where SysNo=%d",row[0]) # 執行語句\ connect.commit() print(row) #cursor.execute(sql001) row=cursor.fetchone() #print(row) connect()
報錯資訊:
File “D:/JiCaiZhuanTi/Case/test.py”,line 22,in connect
row=cursor.fetchone()
File “src\pymssql.pyx”,line 507,in pymssql.Cursor.fetchone
pymssql.OperationalError: Statement not executed or executed statement has no resultset
自己查了不少文章,以前沒有對這塊有所涉及,因為本人是菜鳥,用到哪就看到哪。也仔細看了fetchone() 、fetchall() 還有pymssql的對資料庫的基本炒作。看了好久在最後靈光一閃理解錯誤在哪裡了。
錯誤出在while裡的connect.commit()後直接又row=cursor.fetchone()而while裡是(返回單個的元組,也就是一條記錄(row),如果沒有結果 則返回 None)因為我上一個查詢是update語句,更新sql語句不會返回resultset,所以會報錯。
然後我就這樣改了一下,:
while row: print(“sysno=%s” % (row[0])) cursor.execute(“update xxxxx set Status=-1 where SysNo=%d”,row[0]) # 執行語句 connect.commit() print(row) cursor.execute(sql001) row=cursor.fetchone()
在獲取sql執行獲取結果的 row=cursor.fetchone()我再去呼叫一次查詢再次獲取想要的資料。
我覺得應該有更好的辦法,就是再第一次獲取查詢結果把所需要的sysno都拿出來,然後再while,這樣可以減少對資料庫的呼叫。
目前還沒有寫出來程式碼,不知道思路對不對,大家可以留言討論下。
以上這篇pymysql之cur.fetchall() 和cur.fetchone()用法詳解就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。