簡體   English   中英

使python程序即使無法連接到mysql databse也能繼續運行

[英]Keep python program runing even if it cannot connect to mysql databse

我的程序不斷測量一些數據並將其存儲到mysql數據庫中。 我面臨的問題是,當服務器無法連接到數據庫時,我的Python程序由於某種原因(例如數據庫維護)而停止工作。

我需要的是即使無法連接到數據庫也要保持程序運行。

  def MyDB():
try:
    db = MySQLdb.connect(host="X.X.X.X", user="user1", passwd="passwd1", db="DB1")
    cursor = db.cursor()    
    cursor.execute("INSERT INTO Table1 (timestamp, x1, x2, x3, x4) VALUES ('%s', '%s', '%s', '%s', '%s')" % (x1, x2, x3, x4))
    db.commit()
    db.close()
except MySQLdb.Error as e:
    print (e)
#MyDB

while 1:
   # Here my code doing some measurement
   Measurement()      
   # Here I called MyDB to store my measured data
   MyDB()

我收到的錯誤消息是:OperationalError:(2003,“無法連接到XXXX上的MySQL服務器)

然后我的程序停止。

由於無論程序MyDb發生什么故障,您都希望程序繼續運行,因此我的建議是將調用的函數包裝為try ... except。

while True:
    Measurement()      
    try:
        MyDB()
    except Exception as e:
        print e

您可能想使用traceback模塊來打印捕獲的異常的更好的堆棧跟蹤

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM