如何处理 SQLITE 错误,例如“没有名为列的";没有作为例外提出? [英] How to handled SQLITE errors such as "has no column named" that are not raised as Exceptions?

查看:42
本文介绍了如何处理 SQLITE 错误,例如“没有名为列的";没有作为例外提出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从 Python 中的 SQLite 数据库中捕获错误"的最佳方法是什么,因为它们在 Python 中不被视为异常.

what is the best way to catch the "errors" from the SQLite DB in Python as they are not considered as exceptions in Python.

我在数据库中不存在列的情况下尝试了 INSERT OR IGNORE 语句后的错误输出如下

The error output after I tried an INSERT OR IGNORE statement where a column did not exist in the DB is as follows

('table X has no column named Y,)

以下语句用于执行查询

cursor.execute("INSERT...")

我想到的方法不起作用,因为当游标/查询出错时不返回行数

THe approach I thought of, does not work as a rowcount is not returned when there is an error on the cursor/ query

if cursor.rowcount != 1:
                print("##########Error write_DB\n")

我还能做些什么来捕捉类似的错误.

Is there something else I could do to catch similar erros.

背景:我要插入多行,如果插入查询不成功,我想在日志文件中突出显示.

Background: I am inserting multiple rows and I wanted to highlight in a logfile if the insert query was not sucessfull.

谢谢你的建议

推荐答案

您可以关注 EAFP 方法,使用常规 INSERT(没有忽略"部分)并捕获可以记录的数据库错误:

You can follow the EAFP approach, use regular INSERT (without the "ignore" part) and catch database errors which you can log:

try:
    cursor.execute("INSERT INTO ...", params)
except sqlite3.Error as err:
    logger.error(err.message)

这篇关于如何处理 SQLITE 错误,例如“没有名为列的";没有作为例外提出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆