【问题标题】:How to get SQLite result/error codes in Python如何在 Python 中获取 SQLite 结果/错误代码
【发布时间】:2014-08-18 20:37:02
【问题描述】:

如何从 Python 中的 SQLite 查询中获取(扩展的)结果/错误代码? 例如:

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

现在假设第一列应该是唯一的,并且第一列中已经有一个带有“John”的数据库条目。这将引发 IntegrityError,但我想知道http://www.sqlite.org/rescode.html#extrc 中所述的 SQLite 结果/错误代码。 我想知道,因为我想针对不同的错误采取不同的措施。

【问题讨论】:

    标签: python database sqlite


    【解决方案1】:

    目前,您无法通过 Python 的 sqlite3 模块获取错误代码。根据https://www.sqlite.org/c3ref/errcode.html,C API 分别通过sqlite3_errcodesqlite3_extended_errcodesqlite3_errmsg 公开基本错误代码、扩展错误代码和错误消息。然而,搜索 CPython 源代码发现:

    虽然您要求的功能很有用(确实,我现在需要它来进行调试,并且对它的缺席感到沮丧),但它现在根本不存在。 p>

    【讨论】:

    【解决方案2】:

    #更多相关错误信息可以通过以下方式获取:

        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_data)
            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()
    

    【讨论】:

      猜你喜欢
      • 2023-03-22
      • 1970-01-01
      • 2019-08-18
      • 2012-09-04
      • 2013-01-30
      • 2014-10-22
      • 1970-01-01
      • 2011-04-10
      • 1970-01-01
      相关资源
      最近更新 更多