最近大作業用到了python操作數據庫的內容。涉及的庫是pymmysql,我就不詳細介紹這個庫的操作了,直接奔入主題--->開整
背景:
涉及程序中一個實時查看數據表中state字段==1的功能,我把這個功能單獨擇出來寫成了下面的代碼:
1 # -*- coding=utf-8 -*- 2 import pymysql 3 config={ 4 "host":"127.0.0.1", 5 "user":"root", 6 "password":"root", 7 "database":"Person" 8 } 9 db = pymysql.connect(**config) 10 cursor=db.cursor() 11 while True: 12 a=input("Input something interesting:") 13 sql = "select username from client where state=1" 14 try: 15 cursor.execute(sql) 16 result=cursor.fetchall() 17 except: 18 db.rollback() 19 print(result) 20 cursor.close() 21 db.close()
這是數據庫Person的數據表client內容,關鍵在最后的state內容
執行這個代碼:python3 testdb.py 出現下面效果:
現在看起來是正確的,但是現在不關閉這個python程序,使其阻塞,同時更改數據庫內容
我把Iverson這條數據的狀態state也設為1,然后跑去python繼續執行看有什么結果
發現,雖然直接操控數據庫成功,代碼查詢還是以前的結果沒有變化……
解決方案:
做了很多次修改,把cursor的定義和關閉都放到while循環里面都沒變化還是存在問題;
最后才發現我是少了關鍵的一行代碼---db.commit(),添加后的代碼
1 import pymysql 2 config={ 3 "host":"127.0.0.1", 4 "user":"root", 5 "password":"root", 6 "database":"Person" 7 } 8 db = pymysql.connect(**config) 9 cursor=db.cursor() 10 while True: 11 a=input("Input something interesting:") 12 sql = "select username from client where state=1" 13 try: 14 cursor.execute(sql) 15 db.commit() 16 result=cursor.fetchall() 17 except: 18 db.rollback() 19 print(result) 20 cursor.close() 21 db.close()
執行下:
初始狀態
更改數據庫:
再次測試代碼:
這次終於沒問題了……心累
總結:
第一次看python關於mysql的操作的是菜鳥教程,關於commit方法第一感覺是這個方法只用來提交“數據”,比如插入數據、更新數據需要在execute()后面跟上一個commit();現在看來,commit()方法需要跟在增(insert)、刪(delete)、改(update)、查(select)的任何execute()語句后面。commit是把查詢語句提交到數據庫內,而不只是要向數據庫提交增、添的數據。
就這樣吧……