使用 psycopg2 的字符串格式在 sql 脚本中插入另一个查询
我正在尝试删除一个表并从另一个查询重新创建它。我需要多次执行此操作,因此我使用 python 脚本来自动化它。代码如下;
sql_template = """
DROP TABLE {table_name};
CREATE TABLE IF NOT EXISTS {table_name} AS
(
{another_query}
)
WITH (
OIDS = False
)
TABLESPACE pg_default;
"""
with open("query.sql", "r") as f:
query = f.read()
sql = sql_template.format(table_name = "people", another_query=query)
pgCur.execute(sql)
我收到以下错误:
---------------------------------------------------------------------------
SyntaxError Traceback (most recent call last)
<ipython-input-6-95d24e664779> in <module>
----> 1 pgCur.execute(sql)
SyntaxError: syntax error at or near "("
LINE 430: WITH (
^
sql 语句打印以下 print(sql)
:
DROP TABLE people;
CREATE TABLE IF NOT EXISTS people AS
(
select * from customers c
where c.order_compleate = TRUE
)
WITH (
OIDS = False
)
TABLESPACE pg_default;
I am trying to drop a table and recreate it from another query. I need to do this multiple times so I am using python script to automate it. Code is as follows;
sql_template = """
DROP TABLE {table_name};
CREATE TABLE IF NOT EXISTS {table_name} AS
(
{another_query}
)
WITH (
OIDS = False
)
TABLESPACE pg_default;
"""
with open("query.sql", "r") as f:
query = f.read()
sql = sql_template.format(table_name = "people", another_query=query)
pgCur.execute(sql)
I am getting the following error:
---------------------------------------------------------------------------
SyntaxError Traceback (most recent call last)
<ipython-input-6-95d24e664779> in <module>
----> 1 pgCur.execute(sql)
SyntaxError: syntax error at or near "("
LINE 430: WITH (
^
sql statement prints the following print(sql)
:
DROP TABLE people;
CREATE TABLE IF NOT EXISTS people AS
(
select * from customers c
where c.order_compleate = TRUE
)
WITH (
OIDS = False
)
TABLESPACE pg_default;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论