如何使用带有多个百分比(%)符号的PostgreSQL和Python的like模式匹配?
我试图用如何使用带有多个百分比(%)符号的PostgreSQL和Python的like模式匹配?,python,postgresql,pattern-matching,sql-like,mysql-real-escape-string,Python,Postgresql,Pattern Matching,Sql Like,Mysql Real Escape String,我试图用像LOWER('%%')命令进行模式匹配,但是我认为我在%s中使用python变量这一事实把它搞砸了。我似乎找不到任何百分比符号的转义字符,我的程序没有给我任何错误。这就是问题所在,还是我遗漏了什么。如果我只是像%s那样运行,它确实有效,但是我需要能够像notequals那样搜索 # Ask for the database connection, and get the cursor set up conn = database_connect() if(conn is None):
像LOWER('%%')
命令进行模式匹配,但是我认为我在%s中使用python变量这一事实把它搞砸了。我似乎找不到任何百分比符号的转义字符,我的程序没有给我任何错误。这就是问题所在,还是我遗漏了什么。如果我只是像%s那样运行,它确实有效,但是我需要能够像notequals那样搜索
# Ask for the database connection, and get the cursor set up
conn = database_connect()
if(conn is None):
return ERROR_CODE
cur = conn.cursor()
print("search_term: ", search_term)
try:
# Select the bays that match (or are similar) to the search term
sql = """SELECT fp.name AS "Name", fp.size AS "Size", COUNT(*) AS "Number of Fish"
FROM FishPond fp JOIN Fish f ON (fp.pondID = f.livesAt)
WHERE LOWER(fp.name) LIKE LOWER('%%s%') OR LOWER(fp.size) LIKE LOWER('%%s%')
GROUP BY fp.name, fp.size"""
cur.execute(sql, (search_term, ))
rows = cur.fetchall()
cur.close() # Close the cursor
conn.close() # Close the connection to the db
return rows
except:
# If there were any errors, return a NULL row printing an error to the debug
print("Error with Database - Unable to search pond")
cur.close() # Close the cursor
conn.close() # Close the connection to the db
return None
您可以使用另一个%
转义%
>>> test = 'test'
>>> a = 'LIKE %%s%'
>>> a % test
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: incomplete format
>>>
>>> a = 'LIKE %%%s%%'
>>> a % test
'LIKE %test%'
>test='test'
>>>a=‘像%%s%’
>>>a%测试
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
ValueError:格式不完整
>>>
>>>a=‘像%%s%%’
>>>a%测试
“如%test%”
另外,您还有两个占位符,但是您在execute
中只传递了一个参数,而不是在查询字符串中嵌入符号,您可以将搜索词字符串包装为符号,然后将其传递给cursor.execute()
:
为了便于示例,对查询进行了简化
这更灵活,因为调用代码可以将任何有效的LIKE模式传递给查询
顺便说一句:在Postgresql中,您可以使用ILIKE
for,因此示例查询可以这样编写:
sql = 'SELECT * from FishPond fp WHERE fp.name ILIKE %s'
如文档中所述,ILIKE
是Postgresql扩展,而不是标准SQL。切勿使用裸,除非:
。它将捕获所有内容,甚至内存错误
。至少要使用,例外情况除外:
。
sql = 'SELECT * from FishPond fp WHERE fp.name ILIKE %s'