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?

import psycopg2


conn = psycopg2.connect(database="review_check", user = "xxx", password = "xxx",)
cur = conn.cursor()
print ("Opened database successfully")    


comp_schema = """
as_of_date DATE PRIMARY KEY NOT NULL,
verified_reviews INTEGER,
lsa_total_reviews INTEGER
"""

table_name = 'comp_first'

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

conn.commit()
conn.close()

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:

test = "CREATE TABLE IF NOT EXISTS %s (%s)"%(table_name, comp_schema)
print(test)

>>CREATE TABLE IF NOT EXISTS comp_first (
  as_of_date DATE PRIMARY KEY NOT NULL,
  verified_reviews INTEGER,
  lsa_total_reviews INTEGER
  )
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement