如何在 Python 中获取 SQLite 结果/错误代码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25371636/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get SQLite result/error codes in Python
提问by andere
How do I get the (extended) result/error code from an SQLite query in Python? For example:
如何从 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
Now suppose the first column should be unique and there is already a database entry with "John" in the first column. This will throw an IntegrityError, but I'd like to know the SQLite result/error code as stated on http://www.sqlite.org/rescode.html#extrc. I want to know, because I want to take a different action for different errors.
现在假设第一列应该是唯一的,并且第一列中已经有一个带有“John”的数据库条目。这将引发 IntegrityError,但我想知道http://www.sqlite.org/rescode.html#extrc上所述的 SQLite 结果/错误代码。我想知道,因为我想对不同的错误采取不同的行动。
回答by Mark Amery
Currently, you can'tget error codes through Python's sqlite3module. 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_errcodeand sqlite3_errmsgrespectively. However, searching the CPython source reveals that:
目前,您无法通过 Python 的sqlite3模块获取错误代码。根据https://www.sqlite.org/c3ref/errcode.html,C API分别通过sqlite3_errcode、sqlite3_extended_errcode和公开基本错误代码、扩展错误代码和错误消息sqlite3_errmsg。但是,搜索 CPython 源代码后发现:
sqlite3_extended_errcodenever even gets calledsqlite3_errmsggets called and the result exposed as an Exception messagesqlite3_errcodegets called, but the result is never exposed directly; it's just used to decide which Exception class to raise
sqlite3_extended_errcode甚至从未被调用sqlite3_errmsg被调用并将结果公开为异常消息sqlite3_errcode被调用,但结果永远不会直接暴露;它只是用来决定要引发哪个 Exception 类
While the feature you're asking for would be useful (indeed, I needit right now for debugging and am frustrated by its absence), it simply doesn't exist right now.
虽然您要求的功能很有用(确实,我现在需要它进行调试,但由于它的缺失而感到沮丧),但它现在根本不存在。

