Пример #1
0
    def execute(self, *a, **kw):
        cursor = None
        try:
            if not self._conn:
                cursor = self.retry(*a, **kw)
            else:
                cursor = self._conn.cursor()
                cursor.execute(*a, **kw)
        except (OperationalError, InternalError) as e:
            log.error("begin retry:%s" % e)
            cursor = self.retry(*a, **kw)

        return cursor
Пример #2
0
    def retry(self, *a, **kw):
        cursor = None
        cnt = 0
        while cnt < config.MASTER_DB_HOST_MAX_RETRY_TIMES:
            log.info("begin retry: %s" % cnt)
            time.sleep(2*cnt) #sleep 
            log.info("sleep %s end" % 2*cnt)
            cnt += 1
            try:
                self.connect()
                if not self._conn:
                    continue
                cursor = self._conn.cursor()
                cursor.execute(*a, **kw)
                break
            except (OperationalError, InternalError) as e:
                log.error("Fatal: reconnect db fail:%s" % e)
        log.info("end retried: %s times" % cnt)

        if cursor == None:
            raise Exception("db connection error")
        return cursor
Пример #3
0
 def connect(self, host=None, user=None, passwd=None):
     if not host:
         host = self.host
     if not user:
         user=self.config.MASTER_DB_USER
     if not passwd:
         passwd=self.config.MASTER_DB_PASSWD
     try:
         log.info("conneting [host:%s][user:%s]" % (host, user))
         self._conn and self._conn.close()
         self._conn = MySQLdb.connect(
             host=host,
             port=self.config.DB_PORT,
             user=user,
             passwd=passwd,
             db=self.config.DB_NAME,
             use_unicode=True,
             connect_timeout=5,
             charset="utf8")
         self._conn.autocommit(True)
         log.info("conneted [host:%s][user:%s]" % (host, user))
     except Exception, e:
         log.error("Fatal: connect db fail:%s" % e)