如何修复 sqlalchemy.exc.ObjectNotExecutableError: Not an executable object

问题:

尝试使用 SQLAlchemy 执行查询时,你看到以下错误消息:

error_trace.txt
Traceback (most recent call last):
  File "/usr/local/lib/python3.10/dist-packages/sqlalchemy/engine/base.py", line 1414, in execute
    meth = statement._execute_on_connection
AttributeError: 'str' object has no attribute '_execute_on_connection'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/home/uli/dev/MyProject/SQLIO.py", line 76, in make_sql_connection_and_wait_for_server
    sql.execute("SELECT 1")
  File "/usr/local/lib/python3.10/dist-packages/sqlalchemy/engine/base.py", line 1416, in execute
    raise exc.ObjectNotExecutableError(statement) from err
sqlalchemy.exc.ObjectNotExecutableError: Not an executable object: 'SELECT 1'

解决方案

此问题发生是因为你使用的是为 SQLAlchemy 1.x 编写的代码,但安装的是 SQLAlchemy 2.x。幸运的是,这很容易修复:

不要写

sqlalchemy_execute_bad.py
sql.execute("SELECT 1")

你需要将语句包装在 text() 中:

sqlalchemy_execute_fixed.py
from sqlalchemy.sql import text

# ...
sql.execute(text("SELECT 1"))

记住你需要对每个 execute() 语句这样做。

这样做后,错误将消失。


Check out similar posts by category: Python, Database