Python MySQLdb模塊中的ping()


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 。

關於此錯誤詳細的解釋帖子:
http://sourceforge.net/projects/mysql-python/forums/forum/70461/topic/1536427


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM