用python在開發一個小web站點時碰到一個問題,經過mysql客戶端修改庫中數據後(有作提交),在前臺web頁面刷新仍是之前的數據。而另開一個mysql客戶端查詢是能夠查詢到值的。重啓web服務後能夠看到新值。而一樣使用java的jdbc方式鏈接時一樣的方式是能夠看到新值的。html
因而決定開啓mysql的日誌看看實際運行的SQL有什麼差別.java
先看python鏈接方式的:python
150517 13:34:00 3 Connect root@localhost on dw 3 Query SET NAMES 'utf8' COLLATE 'utf8_general_ci' 3 Query SET @@session.autocommit = OFF 3 Query select id,name from job where id=5 150517 13:34:20 3 Query select id,name from job where id=5 3 Quit
再來看看java的:mysql
150517 13:39:08 5 Connect root@localhost on dw 5 Query /* mysql-connector-java-5.1.25 ( Revision: ${bzr.revision-id} ) */SHOW VARIABLES WHERE Variable_name ='language' OR Variable_name = 'ne t_write_timeout' OR Variable_name = 'interactive_timeout' OR Variable_name = 'wait_timeout' OR Variable_name = 'character_set_client' OR Variable_name = 'character_set _connection' OR Variable_name = 'character_set' OR Variable_name = 'character_set_server' OR Variable_name = 'tx_isolation' OR Variable_name = 'transaction_isolation' OR Variable_name = 'character_set_results' OR Variable_name = 'timezone' OR Variable_name = 'time_zone' OR Variable_name = 'system_time_zone' OR Variable_name = 'lower _case_table_names' OR Variable_name = 'max_allowed_packet' OR Variable_name = 'net_buffer_length' OR Variable_name = 'sql_mode' OR Variable_name = 'query_cache_type' O R Variable_name = 'query_cache_size' OR Variable_name = 'init_connect' 5 Query /* mysql-connector-java-5.1.25 ( Revision: ${bzr.revision-id} ) */SELECT @@session.auto_increment_increment 5 Query SHOW COLLATION 5 Query SET NAMES latin1 5 Query SET character_set_results = NULL 5 Query SET autocommit=1 150517 13:39:09 5 Query select id,name from job where id=5 150517 13:39:29 5 Query select id,name from job where id=5 5 Quit
乍一看上去以爲差很少,沒什麼差別。非常苦悶,因而再想另外的方法。啓動2個python腳原本嘗試,一個寫,另外一個讀。web
結果發現讀的那個腳本能夠立刻讀到新增的數據。因而對比了下讀的腳本發現每次讀完後有作commit。把commit去掉再試,問題重現。再回過頭去看了下python腳本和java腳本生成的mysql日誌的差別。發現sql
python: 3 Query SET @@session.autocommit = OFF java: 5 Query SET autocommit=1
查詢mysql的文檔session
The autocommit mode. If set to 1, all changes to a table take effect immediately. If set to 0, you must use COMMIT
to accept a transaction or ROLLBACK
to cancel itide
autocommit=1時爲自動提交即autocommit=ON.post
接下來嘗試了下postgresql,在autocommit=False時是能夠查看到新數據的。ui
在看postgresql的python驅動的文檔時發現有個不錯的提示,轉帖以下:
Warning
By default, any query execution, including a simple SELECT will start a transaction: for long-running programs, if no further action is taken, the session will remain 「idle in transaction」, a condition non desiderable for several reasons (locks are held by the session, tables bloat...). For long lived scripts, either ensure to terminate a transaction as soon as possible or use an autocommit connection.