使用Flask開發web碰到 MySQL Connection not available

最近在幫別人做一個小型的網站(包括web前端),在使用的過程中,出現了以下的bug:

in Execute_SQL cursor = conn.cursor() ,in cursor raise errors.OperationlError (MySQL Connection not available.)


出現這個bug後,只要涉及到數據庫方面的處理都會出錯。經過一番煞費苦心的查找解決方法時,在這篇文章中找到答案:http://bugs.mysql.com/bug.php?id=67649,解釋如下:

Description:
If you open an unbuffered cursor and you do not read the WHOLE result set before closing the cursor, the next query will fail with

  File "/usr/lib/python3.2/site-packages/mysql/connector/connection.py", line 1075, in cursor
    raise errors.OperationalError("MySQL Connection not available.")
mysql.connector.errors.OperationalError: MySQL Connection not available.

and all subsequent database calls will fail too.
上文說如果你打開了一個cursor,但是沒有把裏面的結果集都read一遍就把它close掉了,後續訪問數據庫都會失敗。

解決方法:

1.在調用cursor.close(),丟棄所有未讀的結果
 我的解決方法,原代碼如下:

def Execute_SQL ( command , var = None , search = True ) :
    cursor = conn.cursor ( )
    if var is None :
        cursor.execute ( command )
    else :
        cursor.execute ( command , var )
    if search :
        values = cursor.fetchall ( )
    else :
        values = cursor.rowcount
        conn.commit ( )
    cursor.close ( )
    return values

改後的代碼:

def Execute_SQL ( command , var = None , search = True ) :
    cursor = conn.cursor ( )
    if var is None :
        cursor.execute ( command )
    else :
        cursor.execute ( command , var )
    if search :
        values = cursor.fetchall ( )
    else :
        # values = cursor.rowcount
        values = cursor.fetchone();
        while values:
            print (values);
            values = cursor.fetchone();
        conn.commit ( )
    cursor.close ( )
    return values


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章