How to get SQLite result / error codes in Python

How to get (extended) result / error code from a SQLite query in Python? For instance:

con = sqlite3.connect("mydb.sqlite") cur = con.cursor() sql_query = "INSERT INTO user VALUES(?, ?)" sql_data = ("John", "MacDonald") try: cur.execute(sql_query, sql) self.con.commit() except sqlite3.Error as er: # get the extended result code here 

Now suppose the first column must be unique, and the first column already has a database record with "John". This will raise an IntegrityError, but I would like to know the SQLite result / error code, as indicated at http://www.sqlite.org/rescode.html#extrc . I want to know because I want to take different actions for different errors.

+6
source share
2 answers

Currently, you cannot get error codes through the sqlite3 Python sqlite3 . Per https://www.sqlite.org/c3ref/errcode.html , the C API provides basic error codes, extended error codes and error messages through sqlite3_errcode , sqlite3_extended_errcode and sqlite3_errmsg respectively. However, a search in the CPython source shows that:

Although the feature you are asking for would be useful (indeed, I need it right now for debugging and frustrated by its absence), it just doesn't exist right now.

+5
source
 try: cur.execute(sql_query, sql_) self.con.commit() except sqlite3.Error as er: print 'er:', er.message 

gives you an error. Or: er.args. This is a list, I donโ€™t know if it can contain more than one item. The first element is the message returned by er.message

Another possibility:

 a,b,c = sys.exc_info() for d in traceback.format_exception(a,b,c) : print d, 

Sqlite error in c

-1
source

Source: https://habr.com/ru/post/974002/


All Articles