2014-03-28 31 views
1

我正在使用Python 2.7.6和MySqldb模塊。我有一個MySQL查詢有時會崩潰。目前很難抓住根本原因。如何避免在執行SQL查詢時崩潰python腳本?我怎樣才能讓它優雅地失敗?如何避免在執行錯誤的SQL查詢時崩潰python腳本?

該代碼看起來像某事;

cursor.execute(query) 
+1

敷在一個'嘗試except'塊:http://docs.python.org/2/tutorial/errors.html –

+0

爲了幫助別人幫助你,發佈更多的代碼。 – Paul

+0

「崩潰」是什麼意思?錯誤被拋出?你的python進程崩潰了?有人的電腦爆炸了?請更多信息:) – aIKid

回答

3

您應該拋出一個異常:

try: 
    cursor.execute(query) 
except mysql.connector.Error: 
    """your handling here""" 

這裏是對MySQL Python Dev guide鏈接:使用try except

1

您可處理運行時錯誤。

最後,你必須使用finally用於清理像關閉連接rollback,釋放所有的資源使用等

這裏是例子,

import mysql.connector 
try: 
    cnx = mysql.connector.connect(user='scott', database='employees') 
    cursor = cnx.cursor() 
    cursor.execute("SELECT * FORM employees") # Syntax error in query 
    cnx.close() 
except mysql.connector.Error as err: 
    print("Something went wrong: {}".format(err)) 
finally: 
    # cleanup (close the connection, etc...)