postgresql 如何捕获独立于使用的数据库/引擎的错误 1062“重复条目”?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8072537/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-20 23:24:10  来源:igfitidea点击:

How to catch error 1062 "duplicate entry" independent from used database/engine?

pythonmysqlpostgresqlsqlalchemy

提问by Florian

In a project I started out with MySQL as database. Instead of checking first, I just do an insert and if I get an IntegrityError exception with code 1062, I know that there is a duplicate entry and warn the user, to do this and that.

在一个项目中,我开始使用 MySQL 作为数据库。我没有先检查,而是执行插入操作,如果我收到代码为 1062 的 IntegrityError 异常,我知道存在重复条目并警告用户执行此操作。

that looks basically like this:

看起来基本上是这样的:

try:
    # add duplicate, nothing bad happens yet, is only in sqla session
    db.session.add(User(email='already_used_email@address_that_has_to_be_unique.com'))
    # commit, now the IntegrityError is raised, when sqla inserts
    db.session.commit()
except IntegrityError as e:
    db.session.rollback()
    # this is what i do with mysql, check the exception for code 1062
    # how can i replace this with something db independent?
    code, msg = e.orig
    if code == 1062:
        # send warning
        pass

Now, for one this makes it already impossible to test with eg. in-memory sqlite. Not nice, but I could live with that.

现在,对于其中之一,已经无法使用例如进行测试。内存中的sqlite。不太好,但我可以忍受。

Second however, I might (have to/want to for other out of scope of this question issues) switch to Postgres. Of course I could just change the code to (also) check for Postgres error codes, but I was hoping there is a way to have SQLALchemy tell me, that a duplicate happened independent from the database. A database dialect abstraction...?

然而,其次,我可能(必须/想要解决此问题范围之外的其他问题)切换到 Postgres。当然,我可以将代码更改为(也)检查 Postgres 错误代码,但我希望有一种方法可以让 SQLALchemy 告诉我,重复发生独立于数据库。数据库方言抽象...?

采纳答案by Richard Huxton

What you want to search for is something called "SQLSTATE" - a set of standard error codes that cover most common RDBMS error states. They don't necessarily provide enough detail for all purposes though, and I don't know if sqlite supports them.

您要搜索的是称为“SQLSTATE”的东西——一组涵盖最常见 RDBMS 错误状态的标准错误代码。不过,它们不一定为所有目的提供足够的细节,我不知道 sqlite 是否支持它们。