2

我正在使用python程序來操縱MySQL數據庫。Python中的光標關閉錯誤MYSQLConnection

當試圖使用windows server 2012任務調度程序它永遠不會工作,報告確實說它是成功的但沒有結果。

使用powershell腳本來調用python程序後,它仍然不工作時,由任務調度程序使用(而它確實工作時,我自己執行它)。

這裏部分報道竊聽:

try: 
    dbconfig = read_db_config() 
    conn = MySQLConnection(**dbconfig) 
    cursor = conn.cursor() 
    delstatmt = "DELETE FROM `event` WHERE filliere='IRC' OR filliere='ETI' OR filliere='CGP'" 
    cursor.execute(delstatmt) 
    conn.commit() 
except Error as e: 
    print(e) 

finally: 
    cursor.close() 
    conn.close() 

誤差是在該行 「cursor.close()」:UnboundLocalError:局部變量 '光標' 之前分配

注引用:它沒有被任務調度器處理時工作。

編輯: Shubham Namdeo解決方案的工作,雖然問題剛剛切換到conn.close()我也把它移動到「嘗試」。我不明白爲什麼它在第一種形式下不起作用,因爲它在我自己執行它時起作用。當出現其他錯誤時,它們與此問題無關。 下面是最終代碼:

try: 
    dbconfig = read_db_config() 
    conn = MySQLConnection(**dbconfig) 
    cursor = conn.cursor() 
    delstatmt = "DELETE FROM `event` WHERE filliere='IRC' OR filliere='ETI' OR filliere='CGP'" 
    cursor.execute(delstatmt) 
    conn.commit() 
    cursor.close() 
    conn.close() 
except Error as e: 
    print(e) 
+0

你檢查過'conn = MySQLConnection(** dbconfig)'是否工作正常?如果不是,那麼將不會創建遊標,並且在'finally'中python會引發錯誤。 –

+0

謝謝,並根據您的編輯我也更新了答案。 –

回答

1

引用我自己在這裏評論

Have you checked whether conn = MySQLConnection(**dbconfig) is working correctly? If it is not, then no cursor will be ever created and in finally python will raise error.

嘗試使用此代碼,而不是你的:

try: 
    dbconfig = read_db_config() 
    conn = MySQLConnection(**dbconfig) 
    cursor = conn.cursor() 
    delstatmt = "DELETE FROM `event` WHERE filliere='IRC' OR filliere='ETI' OR filliere='CGP'" 
    cursor.execute(delstatmt) 
    conn.commit() 
    cursor.close() 
    conn.close() 

except Error as e: 
    print(e) 

這可能會解決你的問題。