最近在钻研python,遇到个很棘手的问题,问过度娘和访过谷歌,迟迟未能解决,问题是这样的:用python实现在长连接到mysql的时候如果出现断线的情况自动重连(断线情况也可能是在执行某种操...
最近在钻研python,遇到个很棘手的问题,问过度娘和访过谷歌,迟迟未能解决,问题是这样的:
用python实现在长连接到mysql的时候 如果出现断线的情况 自动重连 (断线情况也可能是在执行某种操作的时候而不仅仅是数据库重启)
我的编程思路是这样的:
import MySQLdb
import time
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()
c.close()
def run():
last = time.time()
while True :
time.sleep(1)
Now = time.time()
if Now - last > 10 :
last = Now
if (conn.ping()==False):
print'The connection is out'
conn()
conn()
run()
运行了就发现conn.ping()函数不存在,我知道要用到这个函数,但是我不会用,这个是在某个库里面的还是要自己写的,如果是自己写的,应该怎么写呢?
请各位大大高手指点下小弟 小弟不胜感激!!!
程序现在如下:
import MySQLdb
import time
def connect():
conn = MySQLdb.connect(user="root",passwd="1",host="localhost",db="yingtest")
return conn
c = connect()
def restart():
global c
last = time.time()
while True :
time.sleep(1)
Now = time.time()
if Now - last > 10 :
last = Now
try:
c.ping()
except:
print('now restart')
c = connect()
run()
def run():
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()
connect() run() restart()
展开