使用Flask開發web碰到 MySQL Connection not available
阿新 • • 發佈:2019-01-07
最近在幫別人做一個小型的網站(包括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,解釋如下:
上文說如果你打開了一個cursor,但是沒有把裡面的結果集都read一遍就把它close掉了,後續訪問資料庫都會失敗。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.
解決方法:
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