2

我有一个包含文件路径的 postgresql 数据库,如下所示:

create table test (path varchar(1024));
insert into test values('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 的内容如下所示:

select * from test where path like 'c:\\\\foo\\\\bar'

(我使用 cursor.mogrify() 确定了这一点)。

如何避免这种情况并实际使用反斜杠查询字符串?

4

1 回答 1

2

问题在于like,因为反斜杠是模式中的默认转义字符

使用相等运算符:

cu.execute(
    'select * from test where path = %(path)s', 
    {'path': r'c:\foo\bar'}
)

like在模式中使用双反斜杠:

cu.execute(
    'select * from test where path like %(path)s', 
    {'path': r'c:\\foo\\bar'}
)

likeescape子句(例如 with chr(94) = '^'):

cu.execute(
    'select * from test where path like %(path)s escape chr(94)',
    {'path': r'c:\foo\bar'}
)
于 2018-10-06T01:15:19.613 回答