Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/68.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Mysql:多次尝试连接-最佳实践_Python_Mysql_Database Connection - Fatal编程技术网

Python Mysql:多次尝试连接-最佳实践

Python Mysql:多次尝试连接-最佳实践,python,mysql,database-connection,Python,Mysql,Database Connection,我有以下数据库连接代码,最初我没有多次尝试的while循环,但后来我认为最好在失败之前进行多次尝试。我的问题是,实现这一目标的最佳方式是什么?我应该用提姆吗?在再次尝试之前先睡一会儿 while connect_attempts < 3: try: # dbname cann't have hyphen but host name can' db_name = self.language.replace('-','_'

我有以下数据库连接代码,最初我没有多次尝试的while循环,但后来我认为最好在失败之前进行多次尝试。我的问题是,实现这一目标的最佳方式是什么?我应该用提姆吗?在再次尝试之前先睡一会儿

    while connect_attempts < 3:
        try:
            # dbname cann't have hyphen but host name can'
            db_name = self.language.replace('-','_') + 'db'
            print 'Connecting to DB ' + db_name
            logging.info("Connecting to Toolserver MySql Db: " + db_name)
            self.dbConnection = MySQLdb.connect(
                db=db_name,
                host=self.language + "someserver_name.org",
                read_default_file=os.path.expanduser("~/.my.cnf"))
            logging.info("Connection Successful: " + str(self.dbConnection))
            self.dbCursor = self.dbConnection.cursor(cursors.DictCursor)
        except MySQLdb.Error, e:
            logging.error("Unable to establish connection MySQL ERROR - attempt-" + str(connect_attempt), e.value)
            connect_attempts += 1
连接尝试<3时

尝试:
#dbname不能有连字符,但主机名不能
db_name=self.language.replace('-','.''+'db'
打印“连接到数据库”+DB_名称
info(“连接到Toolserver MySql数据库:”+Db_name)
self.dbConnection=MySQLdb.connect(
db=db_名称,
host=self.language+“someserver\u name.org”,
read\u default\u file=os.path.expanduser(“~/.my.cnf”))
logging.info(“连接成功:+str(self.dbConnection))
self.dbCursor=self.dbConnection.cursor(cursors.DictCursor)
除了MySQLdb.Error,e:
logging.error(“无法建立连接MySQL错误-尝试-”+str(连接尝试),e.value)
连接尝试次数+=1

我认为默认参数是如图所示的无超时

您可以传递一个参数来设置超时,例如10秒,在此之后,此连接
将被删除,并将再次尝试建立连接。

根据Sumeet的建议,调用
MySQLdb.connect()时应设置超时。
。但是,连接也可能由于许多其他原因而失败(例如,服务器立即拒绝连接,因为它太忙,或者它处于某种维护模式——想象一下,这不是真实的例子)


您自己的循环也应该包括一个短延迟。我会在您的异常处理程序中将执行延迟几秒钟。

最好使用指向原始源的链接: