Python Except Database Error
Contents |
is 'module.Error'. In MySQL it is 'MySQLdb.Error'. Every DB-API pymysql error handling statement that you execute has the potential to raise an exception. So any time you execute a database query you should surround it python exception handling best practices with a try/exception block. This includes connections, cursor requests, and statement executions. # Get data from database try: cur.execute("SELECT * FROM song") rows = cur.fetchall() except MySQLdb.Error, e: try: print "MySQL Error [%d]: %s" % (e.args[0], e.args[1]) except IndexError: print "MySQL Error: %s" % str(e) # Print results in comma delimited format for row in rows: for col in row: print "%s," % col print "\n" <-- Home -->
here for a quick overview of the site Help Center Detailed answers to any questions you might have Meta
Mysqldb Error Codes
Discuss the workings and policies of this site About Us Learn python raise runtime error example more about Stack Overflow the company Business Learn more about hiring developers or posting ads with us
Python Pass Exception To Calling Function
Stack Overflow Questions Jobs Documentation Tags Users Badges Ask Question x Dismiss Join the Stack Overflow Community Stack Overflow is a community of 6.2 million programmers, just like you, http://www.mikusa.com/python-mysql-docs/exceptions.html helping each other. Join them; it only takes a minute: Sign up Correct way to handle exceptions when working with database up vote 0 down vote favorite 1 When I am executing a simple query (I am using tornado.database module) I handle exceptions like this: try: self.application.db.execute('DELETE FROM table_one WHERE a = 1') except Exception, e: logging.warning('DB http://stackoverflow.com/questions/12745455/correct-way-to-handle-exceptions-when-working-with-database exception: %s' % e) self.set_status(500) return If I want to do a transaction though, it would be smart to rollback it in case of exception: try: self.application.db.execute('START TRANSACTION') self.application.db.execute('DELETE FROM table_one WHERE a = 1') self.application.db.execute('DELETE FROM table_two WHERE b = 2') self.application.db.execute('COMMIT') except Exception, e: logging.warning('DB exception: %s' % e) self.set_status(500) self.application.db.execute('ROLLBACK') return But what if rollback will cause an exception too (e.g. if connection fails)? Do I need to put a nested try-except block inside of the except block? python database exception exception-handling tornado share|improve this question asked Oct 5 '12 at 11:35 bazzilic 427414 To start with, don't catch the general Exception. Instead try to catch whatever specific error you are ready to handle. As for rollback, if the connection is lost then (any normal) database will rollback automatically. –Some programmer dude Oct 5 '12 at 11:41 @JoachimPileborg tornado throws general Exception. Yes, it will, but default wait_timeout for MySQL is 28800 seconds, so other transactions on these tables would be b
implement some mechanism to handle errors gracefully.MySQLdb has MySQLdb.Error exception, a top level http://thepythonguru.com/handling-errors/ exception that can be used to catch all database exception raised by MySQLdb module. from __future__ import print_function import MySQLdb as my try: db = my.connect(host="127.0.0.1", user="root", passwd="", db="world" ) cursor = db.cursor() sql = "select * from city" number_of_rows = cursor.execute(sql) print(number_of_rows) db.close() except my.Error python raise as e: print(e) except : print("Unknown error occurred")123456789101112131415161718192021222324from __future__ import print_functionimport MySQLdb as mytry:db = my.connect(host="127.0.0.1",user="root",passwd="",db="world")cursor = db.cursor()sql = "select * from city"number_of_rows = cursor.execute(sql)print(number_of_rows)db.close()except my.Error as e:print(e)except :print("Unknown error occurred") Two main error in MySQLdbThere are two categories of exception class in MySQLdb you python raise runtime need to be aware:DatabaseError.InterfaceError.DatabaseError: This exception raises when there is problem in data processing, error in sql syntax, mysql internal problems. If a connection is made and a problem arises then DatabaseError will catch it. There are 6 types of DatabaseError:DataError.InternalError.IntegrityError.OperationalError.NotSupportedError.ProgrammingError.DataError: MySQLdb throws this error when there is problem in the data processing, like division by zero, numeric value of of range.InternalError: This exception is raised when there is some internal error in MySQL database itself. For e.g invalid cursor, transaction out of sync etc.IntegrityError: This exception is raised when foreign key check fails.OperationalError: This exception is raised for things that are not in control of the programmer. For e.g unexpected disconnect, error in memory allocation etc, selected database not exists.NotSupportedError: This exception is raised when there is method or api that is not suppo