【问题标题】:popen sql string issuepopen sql字符串问题
【发布时间】:2017-09-07 13:03:04
【问题描述】:

使用 Popen 运行 PostgreSQL 查询。这有效:

maxId = 10

psql = "psql -d db -U user -t -c 'select id, experiment_id from results where id > " + maxId + "'"

ssh = subprocess.Popen(['ssh', 'me@server', psql],
                       shell=False,
                       stdout=subprocess.PIPE,
                       stderr=subprocess.PIPE)
result = ssh.stdout.readlines()

当我添加一个like子句时,它失败了:

psql = "psql -d db -U user -t -c 'select id, experiment_id from results where status like '%Completed%' and id > " + maxId + "'"

['ERROR:  syntax error at or near "%"\n', 'LINE 1: ...t_id" from results where status like %Completed...\n', '                                                             ^\n']

我尝试了几种引用替代方案,但似乎无法正确。

任何帮助将不胜感激。

TD

更新: 终于能够在对 psql 的调用以及在单引号中传递 like 子句的原始问题中保留双引号列名。解决方法如下:

在这里找到提示:Keeping double quotes when passing string to popen in C

psqlcmd = 'psql -U choa -d iondb -t -c ' 
sql = "\"select id, experiment_id, \\\"resultsName\\\" from rundb_results where status like '%Completed%' and id > 5;\""

print(psqlcmd)
print(sql)

ssh = subprocess.Popen(['ssh', 'me@server', psqlcmd, sql],
                       shell=False,
                       stdout=subprocess.PIPE,
                       stderr=subprocess.PIPE)
result = ssh.stdout.readlines()

【问题讨论】:

    标签: python string postgresql popen


    【解决方案1】:

    我试图重现这一点,并设法在 shell 上做到了,但通过 Python 做到这一点是一团糟。我会展示我的发现,以防它帮助您解决问题。

    请注意,区别在于您的 select 语句外部的双引号。

    您需要转义一组单引号,或者更改为双引号并转义一组双引号。

    [root@server tmp]# /opt/rh/postgresql/bin/psql -d database -U user -c 'select * from control where option_name like '%MANAGE%';'
    ERROR:  syntax error at or near "%"
    LINE 1: select * from control where option_name like %MANAGE%;
                                                         ^
    
    
    [root@server tmp]# /opt/rh/postgresql/bin/psql -d database -U user -c "select * from control where option_name like '%MANAGE%';"
     option_name  | status 
    --------------+--------
     MANAGE_NTPD  | false
     MANAGE_DHCP4 | false
     MANAGE_DHCP6 | false
     MANAGE_NAMED | false
    (4 rows)
    

    【讨论】:

    • 谢谢 - 一个引用问题可以确定,但到目前为止还不能正确。也许python正在以某种方式进一步编辑字符串。
    • 是的,我过去也遇到过同样的问题。特别是当您将 psql 前缀单独拆分为一个字符串,然后允许使用不同的 sql 语句对其进行格式化,然后尝试将所有这些插入到它希望您拆分字符串的子进程命令中......(噩梦) ...而且您还尝试通过 ssh 执行此操作..? /手腕
    • 只是给你一个提示,你应该考虑使用 psycopg2。使用起来更方便,比使用 psql 工具在命令行运行命令效果更好
    • 我会调查的。这是供应商提供的机器,我们无法在本地安装任何软件或运行进程......因此 ssh
    猜你喜欢
    • 2011-04-11
    • 1970-01-01
    • 2011-09-04
    • 2021-10-02
    • 2011-12-05
    • 2012-02-15
    • 1970-01-01
    相关资源
    最近更新 更多