简体   繁体   English

如何使用 python 在 psql 数据库中创建表?

[英]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.我正在运行此脚本并希望通过使用变量在 psql 查询中传递值来创建一个表。 So, that I can create multiple table in one go.因此,我可以在一个 go 中创建多个表。 But this cur.execute("CREATE TABLE IF NOT EXISTS(%s, %s)",[table_name, comp_schema]) line is throwing error.但是这cur.execute("CREATE TABLE IF NOT EXISTS(%s, %s)",[table_name, comp_schema])行抛出错误。 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.使用psycopg2.sql模块动态组合查询。 see https://www.psycopg.org/docs/sql.html .请参阅https://www.psycopg.org/docs/sql.html

There's a couple of errors here, in both the SQL syntax and the Python:这里有几个错误,在 SQL 语法和 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
  )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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