python數據查詢操做之 一場缺乏db.commit()引起的血案……

最近大做業用到了python操做數據庫的內容。涉及的庫是pymmysql,我就不詳細介紹這個庫的操做了,直接奔入主題--->開整python



 背景:mysql

       涉及程序中一個實時查看數據表中state字段==1的功能,我把這個功能單獨擇出來寫成了下面的代碼: sql

 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程序,使其阻塞,同時更改數據庫內容fetch

  

  我把Iverson這條數據的狀態state也設爲1,而後跑去python繼續執行看有什麼結果spa

  

  發現,雖然直接操控數據庫成功,代碼查詢仍是之前的結果沒有變化……3d



  解決方案:rest

  作了不少次修改,把cursor的定義和關閉都放到while循環裏面都沒變化仍是存在問題;code

  最後才發現我是少了關鍵的一行代碼---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是把查詢語句提交到數據庫內,而不僅是要向數據庫提交增、添的數據。

  就這樣吧……

相關文章
相關標籤/搜索