如何通过Python的redshift_connector远程运行SQL脚本并解决空查询报错
Redshift外部SQL脚本执行错误修复方案
错误根因
你遇到的query was empty报错核心原因如下:
- 按
;拆分SQL文件内容时,若SQL文件末尾以分号结尾,拆分后会得到一个空字符串片段 - 拆分结果中也可能包含仅由换行、空格、注释组成的无效SQL片段
- 若你将
cursor.close()写在了执行外部SQL脚本的代码之前,已经关闭的游标也无法执行查询
修复后的完整代码
import redshift_connector # 建立Redshift连接 conn = redshift_connector.connect( host = endpoint, database=db_name, user=username, password=password ) conn.autocommit = True cursor: redshift_connector.Cursor = conn.cursor() # 执行外部SQL脚本逻辑 sqlfile = 'test.sql' with open(sqlfile, encoding="utf-8") as f: sql_content = f.read() # 拆分后过滤空白语句,排除无效片段 sql_commands = [cmd.strip() for cmd in sql_content.split(';') if cmd.strip()] for cmd in sql_commands: # 可选:跳过单行注释开头的无效内容 if cmd.startswith('--'): continue cursor.execute(cmd) print(f"执行成功:{cmd[:50]}..." if len(cmd) >50 else f"执行成功:{cmd}") # 所有操作完成后再关闭游标和连接 cursor.close() conn.close()
补充说明
如果你的SQL脚本中包含/* */格式的多行注释,建议提前剔除注释内容后再做拆分,避免注释内的分号导致拆分出的SQL语句不完整,触发语法错误。
内容的提问来源于stack exchange,提问作者Chuck
相关产品推荐
相关产品推荐

