我有类似下面的查询:
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正确地将其视为通配符?
答案 0 :(得分:1)
“在Python中,%
通常是指一个跟在字符串后面的变量。如果你想要一个文字百分号,那么你需要加倍它。%%
”
- Source
LIKE 'string-%%'
否则,如果不起作用,PostgreSQL也支持underscores for pattern matching。
'abc' LIKE 'abc' true
'abc' LIKE 'a%' true
'abc' LIKE '_b_' true
但是,如评论中所述,
pattern
中的下划线(_)代表(匹配)任何单个字符;百分号(%)匹配零个或多个字符的任何序列
根据source code,问题似乎是%
语句中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
答案 1 :(得分:0)
使用最新版本的 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'],)