Skip to content
Advertisement

How to create a table in psql database using python?

I am running this script and want to create a table by passing values in psql query using variables. So, that I can create multiple table in one go. But this cur.execute("CREATE TABLE IF NOT EXISTS(%s, %s)",[table_name, comp_schema]) line is throwing error. How can I write this query to create a table with the given schema?

Advertisement

Answer

There’s a couple of errors here, in both the SQL syntax and the Python:

cur.execute("CREATE TABLE IF NOT EXISTS(%s, %s)",[table_name, comp_schema])

should be

cur.execute("CREATE TABLE IF NOT EXISTS %s (%s)"%(table_name, comp_schema))

It might be easier during development to build the query in a separate variable first, then print it to see if it looks right:

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement