用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是最好的方法了 望指点..
如果你有更好的思路 希望你能共享下 谢谢!
长连接到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每个操作的返回值,发现错误时调用连接函数再
你应该判断每个MySQL每个操作的返回值,发现错误时调用连接函数再
作者: Waistcoat22 发布时间: 2011-07-15
相关阅读 更多
热门阅读
-
office 2019专业增强版最新2021版激活秘钥/序列号/激活码推荐 附激活工具
阅读:74
-
如何安装mysql8.0
阅读:31
-
Word快速设置标题样式步骤详解
阅读:28
-
20+道必知必会的Vue面试题(附答案解析)
阅读:37
-
HTML如何制作表单
阅读:22
-
百词斩可以改天数吗?当然可以,4个步骤轻松修改天数!
阅读:31
-
ET文件格式和XLS格式文件之间如何转化?
阅读:24
-
react和vue的区别及优缺点是什么
阅读:121
-
支付宝人脸识别如何关闭?
阅读:21
-
腾讯微云怎么修改照片或视频备份路径?
阅读:28