溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

MySQLdb 不活躍連接自動斷開的解決方法

發(fā)布時間:2020-07-26 00:09:55 來源:網(wǎng)絡(luò) 閱讀:437 作者:dongfeng012 欄目:編程語言

問題:

通過MySQLdb 連接mysql,如果長時間不活動,會被mysql斷開,再次請求的時候會導(dǎo)致拋出異常"_mysql_exceptions.OperationalError: (2006, 'MySQL server has gone away')"

原因:

這是因為mysql有兩個參數(shù)來自動斷開不活躍的連接,MySQLdb的連接超過這個時間后就會被mysql自動斷開。

interactive_timeout
wait_timeout

可以登陸mysql 執(zhí)行show global variables like "%timeout%" 進(jìn)行查看

解決辦法:

辦法一:

修改mysql的配置,對上面兩個參數(shù)進(jìn)行修改

辦法二:

使用conn的ping()方法進(jìn)行重新連接

conn = MySQLdb.conn(xxxxx)
conn.ping(True)

ping(...)
    Checks whether or not the connection to the server is
    working. If it has gone down, an automatic reconnection is
    attempted.

    This function can be used by clients that remain idle for a
    long while, to check whether or not the server has closed the
    connection and reconnect if necessary.

    New in 1.2.2: Accepts an optional reconnect parameter. If True,
    then the client will attempt reconnection. Note that this setting
    is persistent. By default, this is on in MySQL<5.0.3, and off
    thereafter.

    Non-standard. You should assume that ping() performs an
    implicit rollback; use only when starting a new transaction.
    You have been warned.
向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI