mysqlsqlalchemyremote-access

ObjectNotExecutableError trying to execute SQL on remote MySQL Server with sqlalchemy.create_engine


I have got a remote access to a MySQLServer server and able to execute the SQL correctly using workbench getting desired results. However when I execute the same SQL from the same machine using sqlalchemy I get an error of:

ObjectNotExecutableError    

Here is my code:

from sqlalchemy import create_engine
db_user = os.environ['USER']
db_password = os.environ['PWD']
db_host = os.environ['HOST']
engine = create_engine(f"mysql+pymysql://{db_user}:{db_password}@{db_host}")

with engine.connect() as con:

  rs = con.execute('SELECT schema_name FROM information_schema.schemata;')
  for row in rs:
    print(row)

Any ideas?


Solution

  • You have to use sqlalchemy.text like so con.execute(text("SELECT schema_name FROM information_schema.schemata;"))

    Complete Code

    from sqlalchemy import create_engine, text
    
    db_user = os.environ["USER"]
    db_password = os.environ["PWD"]
    db_host = os.environ["HOST"]
    engine = create_engine(f"mysql+pymysql://{db_user}:{db_password}@{db_host}")
    
    with engine.connect() as con:
        rs = con.execute(text("SELECT schema_name FROM information_schema.schemata;"))
        for row in rs:
            print(row)