歡迎您光臨本站 註冊首頁

pymysql之cur.fetchall() 和cur.fetchone()用法詳解

←手機掃碼閱讀     ml5rwbikls @ 2020-06-03 , reply:0

我就廢話不多說了,大家還是直接看代碼吧!

 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=''): 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',‘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 “srcpymssql.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,這樣可以減少對數據庫的調用。


[ml5rwbikls ] pymysql之cur.fetchall() 和cur.fetchone()用法詳解已經有285次圍觀

http://coctec.com/docs/mysql/show-post-236787.html