سؤال

I am using Python 2.7.6 and MySqldb module. I have a MySQL query that crashes sometimes. It is hard to catch the rootcause for the time being. How can I avoid crashing the python script when executing the SQL query? How can I make it fail gracefully?

The code looks like something;

cursor.execute(query)
هل كانت مفيدة؟

المحلول

You should throw an exception:

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

Here is a link to the MySQL Python Dev guide:

نصائح أخرى

You can handle run time errors by using try except block.

At last you must use finally for cleanups like close the connection , rollback , free all the used resources etc.

Here is the example ,

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...)
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top