Python 如何在psycopg2中查询包含反斜杠的值
我有一个包含文件路径的postgresql数据库,如下所示:Python 如何在psycopg2中查询包含反斜杠的值,python,postgresql,psycopg2,Python,Postgresql,Psycopg2,我有一个包含文件路径的postgresql数据库,如下所示: create table test (path varchar(1024)); insert into test values('c:\foo\bar'); select * from test where path like 'c:\\\\foo\\\\bar' 如果我尝试使用psycopg2匹配路径,它将不起作用: import psycopg2 as pg cx = pg.connect() cu = cx.cursor()
create table test (path varchar(1024));
insert into test values('c:\foo\bar');
select * from test where path like 'c:\\\\foo\\\\bar'
如果我尝试使用psycopg2匹配路径,它将不起作用:
import psycopg2 as pg
cx = pg.connect()
cu = cx.cursor()
cu.execute(
'select * from test where path like %(path)s',
{'path': r'c:\foo\bar'}
)
print(cu.fetchall())
此代码不返回任何结果
问题似乎是Python在内部转义反斜杠,然后psycopg2的参数转义再次转义反斜杠,因此传递给postgresql的内容如下所示:
create table test (path varchar(1024));
insert into test values('c:\foo\bar');
select * from test where path like 'c:\\\\foo\\\\bar'
(我使用cursor.mogrify()确定了这一点)
如何避免这种情况并实际使用反斜杠查询字符串?问题在于类似于,因为反斜杠是一种模式 使用相等运算符:
cu.execute(
'select * from test where path = %(path)s',
{'path': r'c:\foo\bar'}
)
或类似于
,图案中有两个反斜杠:
cu.execute(
'select * from test where path like %(path)s',
{'path': r'c:\\foo\\bar'}
)
或者类似于带有escape
子句的(例如带有chr(94)='^'
):
谢谢在我向维护人员报告后,这些信息现在被添加到官方文档中。