I need to perform SQL statements using SQLAlchemy with a variable table name (come from an external source). I tried several options but no one was successful.
Attempt 1: With text()
:
def empty_table(table_name,testf):
with db.connect() as conn:
s = text("SELECT * FROM $table_name")
rp = conn.execute(s)
receive:
sqlalchemy.exc.ProgrammingError: (psycopg2.errors.SyntaxError) syntax error at or near "$" LINE 1: SELECT * FROM $table_name
Attempt 2: With select()
:
with db.connect() as conn:
s = select([table_name])
rp = conn.execute(s)
receive:
sqlalchemy.exc.ArgumentError: Textual column expression 'my_test_table' should be explicitly declared with text('my_test_table'), or use column('my_test_table') for more specificity
I found in How to do a sqlalchemy query using a string variable as table name? that it possible to resolve the problem using eval(my_variable) but there is no detailed explanation.