简体   繁体   中英

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()

Use the psycopg2.sql module to compose a query dynamically. see https://www.psycopg.org/docs/sql.html .

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
  )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM