【问题标题】:Making sure a query gets executed确保查询被执行
【发布时间】:2013-03-02 12:04:38
【问题描述】:

我的服务器可以正常执行 9/10 次,但有时我会收到错误“在查询期间丢失与 MySQL 服务器的连接”,然后整个过程停止/冻结。

我试图让 MySQL 查询再次执行,如果它使用函数失败,不幸的是,每当我遇到错误时,代码似乎“停止”或卡住。我是不是做错了什么?

这里的字符串类似于:SELECT xx FROM xxx WHERE xxx

try:
    db = MySQLdb.connect (host = "",
         user = "",
         passwd = "",
         db = "" )
except MySQLdb.Error, e:
    print("Error %d: %s" %(e.args[0], e.args[1]))
    sys.exit(1);
cursor = db.cursor()

def mysql_handling(string):
    while 1:
        try:
            cursor.execute(string)
            if 'SELECT' not in string:
                db.commit()           
            break
        except:
            mysql_error_tracking(string)

mysql_error_tracking 是一个函数,用于监控大多数情况下哪些查询失败(不相关)。

【问题讨论】:

  • 可以是以下任何一个:dev.mysql.com/doc/refman/5.0/en/gone-away.html
  • 我已经经历过这个,我只是想检测它什么时候出错,然后再试一次。
  • 另外,只需将mysql_error_tracking 函数放在except 块中;无需为此创建额外的标识符x
  • 那么,虽然如此,您的意思是您也尝试添加超时?
  • 仅通过将 max_allowed_pa​​cket 调整为 64M 来增强内存(因为我同时获得了多个连接)。我会尝试添加超时,如果它有效,我会告诉你

标签: python mysql mysql-python


【解决方案1】:

为您的连接方法添加超时:

db = MySQLdb.connect (host = HOST, user = USER, passwd = PASS, db = DB,
                      connect_timeout = TIMEOUT)

在您的 except 块中执行此操作,以便您重新连接。

为了让您的生活更轻松,请将您的连接代码放在一个单独的函数中,以便您可以重复使用它。像这样的东西(未经测试):

def get_cursor()
    try:
    db = MySQLdb.connect (host = HOST, user = USER, passwd = PASS, db = DB,
                          connect_timeout = TIMEOUT)
    except MySQLdb.Error, e:
        print("Error %d: %s" %(e.args[0], e.args[1]))
        sys.exit(1);
    return db.cursor()

def mysql_handling(cursor, string):
    while True:
        try:
            cursor.execute(string)
            if 'SELECT' not in string:
                db.commit()    
            break
        except MySQLdb.MySQLError:
            cursor.close()
            mysql_error_tracking(string)
            cursor = get_cursor()

def main():
    mysql_handling(get_cursor(), string)

【讨论】:

  • 谢谢!如果查询不正确,这段代码不会无限循环返回吗?
猜你喜欢
  • 1970-01-01
  • 2013-03-21
  • 2020-03-17
  • 1970-01-01
  • 2018-01-18
  • 2013-01-15
  • 2013-12-24
  • 1970-01-01
相关资源
最近更新 更多