1 回答
TA贡献1811条经验 获得超4个赞
将 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()
添加回答
举报