1

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.

1 Answer 1

4

For a simple SELECT * FROM ... query you could just do

import sqlalchemy as sa

# ...

# test data
table_name = 'user_table'

# test code
some_table = sa.Table(table_name, sa.MetaData(), autoload_with=engine)
query = some_table.select()
with engine.begin() as conn:
    result = conn.execute(query).fetchall()
    print(result)
    # [(1, 'gord', '[email protected]'), (2, 'user2', '[email protected]')]
2
  • Can I truncate a table by this way?
    – BT3
    Commented Dec 25, 2019 at 9:35
  • Re: TRUNCATE TABLE - Look here Commented Dec 26, 2019 at 0:58

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.