1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

[Python] Can't put table name into SQLAlchemy Query in Python [duplicate]

Discussão em 'Python' iniciado por Stack, Setembro 16, 2025.

  1. Stack

    Stack Membro Participativo

    In python I am connected to a SQL server through using an engine, and I have manipulated the SQL data in workbench. I now want to move that data manipulation into python. The names of the tables I will be using can change so I want the table name in the query to be a variable. However no matter how I try to escape it I can't put the table name into the query. Here is my code:

    df.to_sql(name='chartfield_data', con=engine, if_exists='replace', index=False)
    sql = text("""
    ALTER TABLE :table ADD Account_Group_2 VARCHAR(20);
    UPDATE :table SET Account_Group_2 =
    (CASE WHEN LEFT(Account, 1) = 4 THEN 'Revenue'
    WHEN LEFT (Account, 1) = 5 THEN 'Salary'
    WHEN LEFT(Account, 1) = 6 THEN 'OTPS'
    ELSE 'Transfer' END);
    """)

    sql_dict = {'table': 'chartfield_data'}

    with engine.begin() as connection:
    connection.execute(sql, sql_dict)


    The table name is chartfield_data. When I use single quotes around it in sql_dict then I get an error saying that the table name in the sql query needs backticks or to be by itself because it is reading as a string 'chartfield_data' which is incorrect. I try to remove the single quotes like so:

    sql_dict = {'table': chartfield_data}


    But that gives me error "chartfield_data is not defined" because it's reading it as a variable. I tried adding the backticks to the name like so:

    sql_dict = {'table': `chartfield_data`}


    But that doesn't work with Python 3.x. I lastly tried using repr(), like so:

    sql_dict = {'table': repr(chartfield_data)}


    But that also threw an error. Is there anyway I can use the table name as a variable in the query and pass it into the query outside of that? Any help would be greatly appreciated!

    Continue reading...

Compartilhe esta Página