+ -
当前位置:首页 → 问答吧 → 用python实现mysql数据库的断线重连问题--希望高人指点

用python实现mysql数据库的断线重连问题--希望高人指点

时间:2011-07-15

来源:互联网

本人在钻研python中 遇到个问题很头疼
长连接到MYSQL,检测到断线的时候(可能是在执行某种查询,或者其他操作时),重连。
我的思路是这样的:
import MySQLdb

import time

import ping

def conn():

  try:

  c=MySQLdb.connect(user="root",passwd="12345",host="localhost",db="yingtest")

  except:

  print "Could not connect to MySQL server."

  exit( 0 )

  try:

  cursor=c.cursor()

  cursor.execute( "SELECT id,detail FROM note where id>1" )

  except Exception,e:

  print'no,it is wrong!'

  print "Rows selected:", cursor.rowcount

  print cursor.fetchall()

  for row in cursor.fetchall():

  print "note : ", row[0], row[1]

  cursor.close()



def run():

  last = time.time()

  while True :

  time.sleep(1)

  Now = time.time()

  if Now - last > 10 :

  last = Now

  if (ping.th_ping==threading.Thread(target=ping_check,args=("localhost",))):

  print'The connection is out'

  conn()

conn()

run()

ping模版是我从网上找的 单独运行可以实现ping的功能 能用在这吗 我觉得这里用ping是最好的方法了 望指点..
如果你有更好的思路 希望你能共享下 谢谢!

作者: yksalun   发布时间: 2011-07-15

ping得通只能说明你跟那台服务器是联通的,但不能保证你跟那台机器的SQL连接是连接状态。

你应该判断每个MySQL每个操作的返回值,发现错误时调用连接函数再

作者: Waistcoat22   发布时间: 2011-07-15