如何在psycopg2中查询包含反斜杠的值

时间:2018-10-05 14:42:17

标签: python postgresql psycopg2

我有一个包含文件路径的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()确定的。)

如何避免这种情况,而实际上查询带有反斜杠的字符串?

1 个答案:

答案 0 :(得分:2)

问题出在like上,因为反斜杠是the default escape character格式。

使用相等运算符:

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'}
)

或带有like子句的escape(例如,带有chr(94) = '^'的子句):

cu.execute(
    'select * from test where path like %(path)s escape chr(94)',
    {'path': r'c:\foo\bar'}
)
相关问题