【问题标题】:How do you get isolated SQL syntax error in SQLAlchemy如何在 SQLAlchemy 中获得孤立的 SQL 语法错误
【发布时间】:2018-10-20 21:27:00
【问题描述】:

使用 SQLAlchemy 我想隔离任何 SQL 语法错误。比如……

try:
  [row for row in db.execute(text("select * from userds"), **args)]
except ProgrammingError as error:
  print(error)

我明白了

(psycopg2.ProgrammingError) relation "userds" does not exist
LINE 1: select * from userds
                      ^
 [SQL: 'select * from userds'] (Background on this error at: http://sqlalche.me/e/f405)

而我只对……感兴趣。

relation "userds" does not exist

有人知道这是否可行吗?

【问题讨论】:

  • print(error.params[0])print(error._message)? --> github.com/zzzeek/sqlalchemy/blob/master/lib/sqlalchemy/…
  • 这不起作用。 error.params 是一个空字典,error._message 实际上是一个函数,它仍然在行首包含驱动程序信息。感谢您提供指向源的链接。
  • 我应该注意,我试图避免在错误消息 bc 上进行字符串修改。我正在编写的应用程序可以连接 w/multi。数据库驱动程序是动态的,所以我事先不知道驱动程序..
  • 你说得对,我查看的是SQLAlchemy 的源代码,而不是你正在使用的psycopg2,它应该只是error.pgerror,如下所示 --> @ 987654322@
  • 谢谢,但我确实希望它独立于数据库驱动程序。我以 postgres 为例,但它应该适用于 mysql、sqlite 等。

标签: python sql exception-handling sqlalchemy


【解决方案1】:

我找到了解决问题的方法。您必须捕获 StatementError 并打印出错误对象上的 orig 属性,就像这样..

from sqlalchemy.exc import StatementError

try: 
 [r for r in db.execute("invalid statement")]
except StatementError as error:
 print(error.orig)

https://github.com/zzzeek/sqlalchemy/blob/699272e4dcb9aa71ebbc0d9487fb6de82d3abc2b/lib/sqlalchemy/exc.py#L280

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-05-15
    • 1970-01-01
    • 2017-04-23
    • 2011-07-10
    • 1970-01-01
    • 1970-01-01
    • 2018-07-13
    相关资源
    最近更新 更多