如何在Python中获取SQLite结果/错误代码 [英] How to get SQLite result/error codes in Python
问题描述
如何从Python中的SQLite查询中获取(扩展)结果/错误代码?
例如:
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 = "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上所述的SQLite结果/错误代码://www.sqlite.org/rescode.html#extrc 。我想知道
,因为我想对不同的错误采取不同的操作。
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.
推荐答案
当前,您无法通过Python的 sqlite3
模块获取错误代码。根据 https://www.sqlite.org/c3ref/errcode.html ,C API通过 sqlite3_errcode
, sqlite3_extended_errcode
和公开基本错误代码,扩展错误代码和错误消息。 sqlite3_errmsg
。但是,搜索CPython源代码会发现:
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
从未被调用 - <$调用c $ c> sqlite3_errmsg 并将结果显示为异常消息
-
sqlite3_errcode
被调用,但是结果永远不会直接暴露出来;它只是用来决定要引发哪个Exception类
sqlite3_extended_errcode
never even gets calledsqlite3_errmsg
gets called and the result exposed as an Exception messagesqlite3_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.
这篇关于如何在Python中获取SQLite结果/错误代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!