简体   繁体   中英

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

I have program continuously measuring some data and storing them to the mysql database. The problem I'm facing is, when the server cannot connect to the database my Python program stops working for some reason (eg DB maintenance).

What I need here is to just keep my program running even if cannot connect to the database.

  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()

The error message I get is : OperationalError: (2003, "Can't connect to MySQL server on 'XXXX')

And my program stop.

Since you want your program to continue running no matter what failure happens in the function MyDb, My suggestion would be to wrap the function calling with try...except.

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

You might want to use the traceback module to print a better stacktrace of the caught exception.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM