如何在python psycopg2中使用ilike和通配符模式?

问题描述

我已经提到了这个 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 回溯(最近调用 最后)在 ----> 1 cursor.execute('select * from test where code in ("0091","5059")')

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

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

cursor.execute('select * from test where code in ('0091','0092','0FY00Z0','0FY00Z1','0FY00Z2','5051','5059')') ^ 语法错误:令牌无效

当我尝试使用 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 中使用它们时,我遇到了问题。

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

解决方法

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 查询中使用三引号很常见,但不是必须的,因为当查询包含单引号值或双引号标识符时,三引号会起作用。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...