【问题标题】:How to use ilike and wildcard pattern in python psycopg2?如何在 python psycopg2 中使用 ilike 和通配符模式?
【发布时间】:2021-08-17 22:28:11
【问题描述】:

我已经提到了这个post 和这个post,但它没有帮助

我正在尝试编写以下代码

import psycopg2
param_dic = {
    "host"      : "localhost",
    "database"  : "test",
    "user"      : "test",
    "password"  : "****"
}
conn = psycopg2.connect(**param_dic)
cursor = conn.cursor()
cursor.execute('select * from test where code in ("0091","0092","0FY00Z0","0FY00Z1","0FY00Z2","5051","5059")')

在上面的cursor execute 命令中,无论我使用single quote 还是double quotes 我都会得到如下所示的错误

ndefinedColumn Traceback(最近调用 最后)在 ----> 1 cursor.execute('select * from test where code in ("0091","0092","0FY00Z0","0FY00Z1","0FY00Z2","5051","5059")')

UndefinedColumn:列“0091”不存在第 1 行:...来自 测试代码在哪里 ("0091","00...

当我将引号更改为 single quote 时,出现以下错误

cursor.execute('select * from test where code in ('0091','0092','0FY00Z0','0FY00Z1','0FY00Z2','5051','5059')') ^ SyntaxError: 无效标记

当我尝试使用ilike 运算符时,我收到以下错误

cursor.execute ('select code from test where long_title ilike '%live%' and long_title ilike '%ransplan%'')

NameError: name 'live' 没有定义

但上述所有查询在我的 pgadmin postgresql 编辑器中都可以正常工作。因此,原生形式的 SQL 没有问题,但是当我尝试使用 cursor.execute 在 python 中使用它们时,我遇到了问题。

你能帮我解决这个问题吗?

【问题讨论】:

    标签: python sql postgresql psycopg2 quoting


    【解决方案1】:

    Postgresql 要求字符串值用单引号引起来。

    Python 字符串可以用单引号 ('...')、双引号 ("...") 或三重单引号或双引号 ('''...''') 来限制。

    为了让 Postgresql 满意,请使用单引号来引用查询中的值,并将查询字符串与其他类型之一绑定。

    cursor.execute("""select * from test where code in ('0091','0092','0FY00Z0','0FY00Z1','0FY00Z2','5051','5059')""")
    
    cursor.execute ("""select code from test where long_title ilike '%live%' and long_title ilike '%ransplan%'""")
    

    在 SQL 查询中使用三引号很常见,但不是强制性的,因为当查询包含单引号值或双引号标识符时,它们将起作用。

    【讨论】:

    最近更新 更多