and*_*ere 10 python database sqlite
如何从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
Run Code Online (Sandbox Code Playgroud)
现在假设第一列应该是唯一的,并且在第一列中已经有一个带有"John"的数据库条目.这将引发IntegrityError,但我想知道http://www.sqlite.org/rescode.html#extrc中所述的SQLite结果/错误代码.我想知道,因为我想针对不同的错误采取不同的行动.
目前,您无法通过Python的sqlite3模块获取错误代码.每https://www.sqlite.org/c3ref/errcode.html,所述C API暴露基本的错误代码,扩展错误代码,并且通过错误消息sqlite3_errcode,sqlite3_extended_errcode和sqlite3_errmsg分别.但是,搜索CPython源会显示:
sqlite3_extended_errcode 从来没有被召唤过sqlite3_errmsg 被调用,结果作为异常消息公开sqlite3_errcode被调用,但结果永远不会直接暴露; 它只是用来决定引发哪个Exception类虽然你要求的功能是有用的(事实上,我现在需要它来进行调试,但由于缺少它而感到沮丧),它现在根本不存在.
小智 6
#有关相关错误的更多信息可以通过以下方式获取:
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()
Run Code Online (Sandbox Code Playgroud)