How to fix sqlalchemy.exc.ObjectNotExecutableError: Not an executable object

Problem:

When trying to execute a query using SQLAlchemy, you see the following error message:

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'

Solution:

This issue occurs because you’re using code which was written for SQLAlchemy 1.x, but you have installed SQLAlchemy 2.x. Fortunately. this is rather easy to fix:

Instead of writing

sql.execute("SELECT 1")

you need to wrap the statement in text():

from sqlalchemy.sql import text

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

Remember you need to do that for every execute() statement.

After doing that, the error will disappear.