【问题标题】:Psycopg2 "Can't execute an empty query"Psycopg2“无法执行空查询”
【发布时间】:2020-04-04 01:08:14
【问题描述】:

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

谁能帮我解决这个问题?

【问题讨论】:

  • 看sqlStatements,最后一个元素会是空字符串
  • 正是@IainShelvington。我在打印每条语句时都看到了这个空字符串,但我不知道如何摆脱它。

标签: python sql postgresql psycopg2


【解决方案1】:

当您通过; 拆分您的sql 文件时,创建的列表将具有空字符串作为最后一个元素,并且它将无法作为有效查询执行。 为了避免这种情况,假设您文件中的所有 sqls 最后都有;,请尝试以下操作:

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()

【讨论】:

  • 它就像一个魅力!我也会记住您的第二个建议,但对于手头的情况,我将无法使用它,因为每个脚本中的 SQL 语句本质上非常长且多行。非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-24
  • 2018-02-11
  • 2016-01-27
相关资源
最近更新 更多