Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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)
share|improve this question
1  
Wrap it in a try except block: docs.python.org/2/tutorial/errors.html –  Jason Sperske Mar 28 at 7:29
    
To help others help you, post more code. –  Paul Mar 28 at 7:30
    
What do you mean by "crashing"? An error is thrown? Your python process crashed? Someone's computer exploded? Please be more informative :) –  aIKid Mar 28 at 7:37

2 Answers 2

up vote 3 down vote accepted

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:

share|improve this answer

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...)
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.