即使无法连接到mysql数据库,也要保持python程序运行

时间:2016-10-20 10:00:39

标签: python python-2.7

我有程序不断测量一些数据并将它们存储到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()

我得到的错误信息是: 操作错误:(2003年,"无法在' X.X.X.X'上连接到MySQL服务器)

我的程序停止了。

1 个答案:

答案 0 :(得分:0)

由于你希望你的程序继续运行,无论函数MyDb发生什么故障,我的建议是用try ...来包装函数调用。

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

您可能希望使用 traceback 模块打印捕获的异常的更好堆栈跟踪。