python - Psycopg2 "Can' t 执行空查询”

标签 python sql postgresql psycopg2

我将一些查询保存在单个 .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/

相关文章:

python - Tornado eventloop 在产生多个 gen.Task 时引发 "NoneType object is not iterable"

postgresql - 无法删除 Postgres 中的 GIN 索引

PostgreSQL 错误 : could not connect to database template1: could not connect to server: No such file or directory

SQL 按日期复制行到今天

mysql - 为每条记录返回一个新行

sql - SQL Server是否默认在表的所有列上创建非聚集索引

sql - postgresql 使用 for 循环更改所有序列

python gflags 模块帮助标志不起作用

python - 从并行的 Celery 任务执行中收集结果

python - 如何为 CatBoostRegressor 指定多个 eval_metric?