mysqldb 默认为8个小时为自动断开间隔时间,如何解决这个问题

mysqldb 默认为8个小时为自动断开间隔时间,如何解决这个问题:

(1)mysqldb提供了一个方法采用类似:

try: 
   conn.ping() 
except Excption,e: #实际对应的  MySQLdb.OperationalError 这个异常
   conn = new conn 

解决方案代码:

def executeSQL(self,sql=""):

        try:
            self.conn.ping()
        except Exception,e:
            self.log.error("Msql出了问题")
            self.log.error(str(e))
            while True:
                try:
                    self.conn = MySQLdb.connect(self.config.get('mysql_server'),self.config.get('mysql_user'),self.config.get('mysql_pass'),self.config.get('mysql_db_name'),connect_timeout=60,compress=True,charset="UTF8")
                    break
                except Exception,e:
                    self.log.error("尝试重连接失败")
                    time.sleep(2)
                    continue
            self.cursor=self.conn.cursor()
        try:
            self.cursor.execute(sql)
            self.conn.commit()
            return 1
        except Exception,e:
            self.log.error(str(e))
            return 0

(2)tonaldb解决方法,if now time - 起始连接时间 > 数据库自动断开间隔 则进行重连操作。

 def _ensure_connected(self):

            # Mysql by default closes client connections that are idle for
            # 8 hours, but the client library does not report this fact until
            # you try to perform a query and it fails.  Protect against this
            # case by preemptively closing and reopening the connection
            # if it has been idle for too long (7 hours by default).
            if (self._db is None or
                (time.time() - self._last_use_time > self.max_idle_time)):
                self.reconnect()
            self._last_use_time = time.time()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值