2015-02-05 172 views
6

我每天都會收到以下消息。我的腳本正在運行cron作業。誰能幫助解決這個問題嗎?MySQL服務器已經消失 - Python

File "/usr/lib64/python2.6/site-packages/MySQLdb/cursors.py", line 174, in execute 
    self.errorhandler(self, exc, value) 
    File "/usr/lib64/python2.6/site-packages/MySQLdb/connections.py", line 36, in defaulterrorhandler 
    raise errorclass, errorvalue 
_mysql_exceptions.OperationalError: (2006, 'MySQL server has gone away') 

我的代碼:

def get_id(test_mysql_conn,id): 
    cursor = test_mysql_conn.cursor() 
    cursor.execute("""select id from test where id = %s """, (id)) 
    row = cursor.fetchone() 
    if row is not None: 
     return row[0] 
    return 0 
+1

看看這個答案:http://stackoverflow.com/a/982873/974317 – 2015-02-05 12:47:19

+0

檢查[此] (http://dev.mysql.com/doc/refman/5.0/en/gone-away.html)。 – 2015-02-05 13:12:11

+0

有關詳細信息,當您超出最大數據包大小時可能會發生此錯誤:請參閱[這裏](http://serverfault.com/a/528183/341327) – PlasmaBinturong 2016-06-08 14:41:35

回答

1

嘗試follwing

if (os.getenv('SERVER_SOFTWARE') and os.getenv('SERVER_SOFTWARE').startswith('Google App Engine/')): 
      db = MySQLdb.connect(unix_socket = UNIX_SOCKET + INSTANCE_NAME, host =" HOST/IP", db = "DB_Name", user = "User_Name") //if your mysql is on google server 
     else: 
      db = MySQLdb.connect(host = "HOST/IP", port = "Port_number", db = "DB_name", user = "User_Name", passwd = "password") 

    cursor = db.cursor() 
    cursor.connection.autocommit(True) 

except Exception, err: 
    logging.info("Error In DataBase Connection : " + traceback.format_exc()) 
    return 'DataBaseProblem'   
try: 
    sql = query+str(req_args) 
    logging.info("QUERY = "+str(sql)) 
    cursor.execute(sql) 
    procedureResult = cursor.fetchall(); 
    if str(procedureResult) == '()': 
     logging.info("Procedure Returned 0 Record") 
     procedureResult = 'DataBaseProblem' 


    #logging.info("procedureResult : " + str(procedureResult)) 
except Exception, err: 
    #trackBack = str (traceback.format_exc()) 
    #raise Exception('DataBaseProblem',trackBack) 
    procedureResult="DataBaseProblem" 

爲MySQL端口號3306

0

當你打開一個MySQL連接,但不關閉此情況它。 MySQL的事物有一個超時。

你可以做的一件事就是在完成使用時關閉連接。另一個將使用一個支持此或內置的ORM(SQLAlchemy是我相信)