python数据库自动重连_用python编写与mysql数据库连接并实现断线重连的问题

最近在钻研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()

展开

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值