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

posted on 2012-04-12 22:40  o笨熊o  阅读(12323)  评论(1编辑  收藏  举报