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

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值