1

I have a code in Python that inserts data into a remote Postgresql database. I made the program accept a user input and created a table with the user input as the table name. However, when I INSERT INTO the table, I have to specify the name of the table to insert into. How do I specify the table I just created? For clarification, here is the line in my code I am having trouble with:


cursor.execute("INSERT INTO [name_of_table_I_just_created] (column1, column2) VALUES (%s, %s);")

I created the table using cursor.execute(). trial_name is the user input:


    cursor.execute(f"""
            CREATE TABLE {trial_name} (
                id SERIAL PRIMARY KEY,
                column1 VARCHAR,
                column2 VARCHAR
            );
        """)

I hope my question is clear. Thanks in advance.

I tried specifying the table I just created using %s, but that was for fields

David H.
  • 11
  • 2
  • 1
    Use the `psycopg2` [sql](https://www.psycopg.org/docs/sql.html) module. – Adrian Klaver Aug 09 '23 at 23:16
  • Why don't you like the solution you have posted? It is correct, assuming you have taken steps to make sure it's safe. It is unusual to have table names be a variable -- how are you going to fetch that table later? – Tim Roberts Aug 10 '23 at 00:03

0 Answers0