1. 程式人生 > >Python MySQLdb模組中的ping()

Python MySQLdb模組中的ping()

本文轉自:http://www.cnblogs.com/bugmaker/articles/2444905.html

MySQLdb.connection.ping()函式可以用來檢測在訪問前檢測資料庫的連線是否存在

使用help函式獲得幫助資訊如下:

Checks whether or not the connection to the server is
working. If it has gone down, an automatic reconnection is
attempted.
This function can be used by clients that remain idle for a
long while, to check whether or not the server has closed the
connection and reconnect if necessary.

New in 1.2.2: Accepts an optional reconnect parameter. If True,
then the client will attempt reconnection. Note that this setting
is persistent. By default, this is on in MySQL<5.0.3, and off
thereafter.
Non-standard. You should assume that ping() performs an
implicit rollback; use only when starting a new transaction.
You have been warned.

 

另外,在使用ping()的時候,可能由於版本問題出現ping()函式需要引數,從而發生異常,解決辦法如下:

try:

  conn.ping()

except:

  conn.ping(True)

 

 

 

以下是轉載部分:

By default, MySQL-5.0 does not automatically reconnect.

mysql連線如果長時間idle的話,(時間:預設為8小時),會自動斷開,而且不會為原連線自動恢復。

在python中,如果應用程式某個模組使用了持久化的db連結,則失效後,繼續使用,會報錯: 2006,MySQL server has gone away

解決辦法: 比較ugly

在每次連線之前,判斷該連結是否有效。 MySQLdb提供的介面是 Connection.ping(),
(奇怪,ping() 這個方法在 MySQLdb 的文件中居然沒有文件化, 害我找了好久)

採用 類似:
try:
   conn.ping()
except Excption,e:      #實際對應的  MySQLdb.OperationalError 這個異常
   conn = new conn

的方法解決

為了測試出 ping()的效果,
我在程式碼中先關閉了 conn, 示意如下:

try:
   conn.close()
   conn.ping()
except Excption,e:      #實際對應的  MySQLdb.OperationalError 這個異常
   print e
   conn = new conn

結果爆出了另外一個錯誤:
InterfaceError: (0, '')

google了一大圈都沒找到正確原因,一度還以為是:
  File "/usr/lib/pymodules/python2.6/MySQLdb/cursors.py", line 147, in execute charset = db.character_set_name()
的問題, (因為錯誤的traceback 指向了此處...)

實際上: 對任何已經close的conn進行 db相關 操作,包括ping()都會爆出這個錯誤。
(這說明 長時間idle導致的conn失效與 conn.close()之後的狀態是不一樣的)
精確catch 這個錯誤的Exception 是   MySQLdb.Error 。