我有一个类似于下面的查询:
def connection():
pcon = pg8000.connect(host='host', port=1234, user='user', password='password', database = 'database')
return pcon, pcon.cursor()
pcon, pcur = connection()
query = """ SELECT * FROM db WHERE (db.foo LIKE 'string-%' OR db.foo LIKE 'bar-%')"""
db = pd.read_sql_query(query, pcon)
但是,当我尝试运行代码时,我得到:
DatabaseError: '%'' not supported in a quoted string within the query string
我尝试用 \ 和额外的 % 转义符号,但没有运气。如何让 pg8000 正确将其视为通配符?
"在Python中,%
通常是指字符串后面的变量。如果你想要一个文字百分号,那么你需要加倍它。 %%
"
--源
LIKE 'string-%%'
否则,如果这不起作用,PostgreSQL还支持模式匹配的下划线。
'abc' LIKE 'abc' true
'abc' LIKE 'a%' true
'abc' LIKE '_b_' true
但是,正如评论中提到的,
pattern
中的下划线 (_) 代表(匹配)任何单个字符;百分号 (%) 匹配任何零个或多个字符的序列
但是,根据源代码,问题似乎出在LIKE
语句中%
后面的单引号。
if next_c == "%":
in_param_escape = True
else:
raise InterfaceError(
"'%" + next_c + "' not supported in a quoted "
"string within the query string")
因此,如果next_c == "'"
而不是next_c == "%"
,那么您会收到错误
'%'' not supported in a quoted string within the query string
使用最新版本的 pg8000,您在LIKE
中使用%
应该没有任何问题。例如:
>>> import pg8000.dbapi
>>>
>>> con = pg8000.dbapi.connect(user="postgres", password="cpsnow")
>>> cur = con.cursor()
>>> cur.execute("CREATE TEMPORARY TABLE book (id SERIAL, title TEXT)")
>>> for title in ("Ender's Game", "The Magus"):
... cur.execute("INSERT INTO book (title) VALUES (%s)", [title])
>>>
>>> cur.execute("SELECT * from book WHERE title LIKE 'The %'")
>>> cur.fetchall()
([2, 'The Magus'],)