Python Mysqldb Error Handling
Contents |
is 'module.Error'. In MySQL it is 'MySQLdb.Error'. Every DB-API
Python Database Error
statement that you execute has the potential to raise an exception. So any time you execute a database query you should surround it mysqldb operationalerror 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 Discuss the workings and policies of this
Mysqldb Execute
site About Us Learn more about Stack Overflow the company Business Learn
Mysqldb Documentation
more about hiring developers or posting ads with us Stack Overflow Questions Jobs Documentation Tags Users Badges Ask Question x python mysql insert Dismiss Join the Stack Overflow Community Stack Overflow is a community of 6.2 million programmers, just like you, helping each other. Join them; it only takes a minute: Sign up Error http://www.mikusa.com/python-mysql-docs/exceptions.html handling in Python-MySQL up vote 1 down vote favorite I am running a little webservice based on python flask, where I want to execute a small MySQL Query. When I get a valid input for my SQL query, everything is working as expected and I get the right value back. However, if the value is not stored in the database I receive a TypeError http://stackoverflow.com/questions/30996401/error-handling-in-python-mysql Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1836, in __call__ return self.wsgi_app(environ, start_response) File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1820, in wsgi_app response = self.make_response(self.handle_exception(e)) File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1403, in handle_exception reraise(exc_type, exc_value, tb) File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1817, in wsgi_app response = self.full_dispatch_request() File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1478, in full_dispatch_request response = self.make_response(rv) File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1566, in make_response raise ValueError('View function did not return a response') ValueError: View function did not return a response I tried to tap into error handling myself and use this code for my project, but it seems like this doesn't work properly. #!/usr/bin/python from flask import Flask, request import MySQLdb import json app = Flask(__name__) @app.route("/get_user", methods=["POST"]) def get_user(): data = json.loads(request.data) email = data["email"] sql = "SELECT userid FROM oc_preferences WHERE configkey='email' AND configvalue LIKE '" + email + "%';"; conn = MySQLdb.connect( host="localhost", user="root", passwd="ubuntu", db="owncloud", port=3306) curs = conn.cursor() try: curs.execute(sql) user = curs.fetchone()[0] return user except MySQLdb.Error, e: try: print "MySQL Error [%d]: %s" % (e.args[0], e.args[1]) return None except IndexError: print "MySQL Error: %s" % str(e) return None except TypeError, e: print(e) return None except ValueError, e: print(e) return None finally: cur
implement some mechanism to handle errors gracefully.MySQLdb has MySQLdb.Error exception, a top http://thepythonguru.com/handling-errors/ level exception that can be used to catch all database exception raised by MySQLdb module. from __future__ import print_function import MySQLdb as http://alexbraunstein.com/2011/08/17/simple-mysqldb-python-script/ 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) error handling db.close() except my.Error 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 pymysql error handling in MySQLdb you 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