How to get SQLite result/error codes in Python

前端 未结 2 1586
刺人心
刺人心 2021-02-13 04:42

How do I get the (extended) result/error code from an SQLite query in Python? For example:

con = sqlite3.connect(\"mydb.sqlite\")
cur = con.cursor() 
sql_query =         


        
相关标签:
2条回答
  • 2021-02-13 05:03

    #More info on related error can be taken by:

    import sqlite3
    import traceback
    import sys
    
    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:
        print('SQLite error: %s' % (' '.join(er.args)))
        print("Exception class is: ", er.__class__)
        print('SQLite traceback: ')
        exc_type, exc_value, exc_tb = sys.exc_info()
        print(traceback.format_exception(exc_type, exc_value, exc_tb))
    con.close()
    
    0 讨论(0)
  • 2021-02-13 05:12

    Currently, you can't get error codes through Python's sqlite3 module. Per https://www.sqlite.org/c3ref/errcode.html, the C API exposes basic error codes, extended error codes, and error messages through sqlite3_errcode, sqlite3_extended_errcode and sqlite3_errmsg respectively. However, searching the CPython source reveals that:

    • sqlite3_extended_errcode never even gets called
    • sqlite3_errmsg gets called and the result exposed as an Exception message
    • sqlite3_errcode gets called, but the result is never exposed directly; it's just used to decide which Exception class to raise

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

    0 讨论(0)
提交回复
热议问题