我将一些查询保存在单个 .sql 脚本中,而不是直接将它们写入 .py 脚本的变量内。
现在我想使用Python读取这个sql脚本,用分号分隔每个sql语句,然后将每个脚本传递给Psycopg2游标以顺序执行。
Python 脚本似乎可以正确读取文件,但当我尝试执行语句时,会抛出“无法执行空查询”错误。
也许问题是:这个 sql 脚本中有很多换行符。其中的语句写法如下:
DROP TABLE IF EXISTS
target_schema.some_table
;
SELECT
column
FROM
schema.table
;
这是Python代码:
import psycopg2
import pathlib
conn = psycopg2.connect(
user=user
,password=password
,host=host
,port=port
,database=database
)
pg_cursor = conn.cursor()
scriptContents = Path('my_folder\my_sql_script.sql').read_text(encoding='utf-8')
sqlStatements = scriptContents.split(sep=';')
for statement in sqlStatements:
try:
pg_cursor.execute(f'{statement}')
conn.commit()
except psycopg2.Error as errorMsg:
print(errorMsg)
conn.rollback()
谁能帮我解决这个问题吗?
最佳答案
当您按 ;
拆分 sql 文件时,创建的列表的最后一个元素将为空字符串,并且它将无法作为有效查询执行。
为了避免这种情况,假设文件中的所有 sql 最后都有 ;
,请尝试以下操作:
for statement in sqlStatements[:-1]:
# it will slice out the last element of your sqlStatements list
try:
pg_cursor.execute(f'{statement}')
conn.commit()
except psycopg2.Error as errorMsg:
print(errorMsg)
conn.rollback()
另一种解决方案是将语句以新行分隔,然后按以下方式逐一读取:
my_sql_script.sql:
DROP TABLE IF EXISTS target_schema.some_table
SELECT column FROM schema.table
为了运行语句,请使用:
with open('my_folder\my_sql_script.sql','r', encoding='utf-8') as f:
for statement in f.readlines():
try:
pg_cursor.execute(f'{statement.rstrip()}')
conn.commit()
except psycopg2.Error as errorMsg:
print(errorMsg)
conn.rollback()
关于python - Psycopg2 "Can' t 执行空查询”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61022590/