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()
添加回答
舉報