如何使用与 PostgreSQL 匹配的 like 模式和具有多个百分比 (%) 符号的 Python?

How to use like pattern matching with PostgreSQL and Python with multiple percentage (%) symbols?

我正在尝试使用 LIKE LOWER('% %') 命令进行模式匹配,但是我认为我正在使用带有 %s 的 python 变量这一事实正在搞砸它。我似乎找不到百分比符号的任何转义字符,而且我的程序没有给我任何错误。这是问题还是我还缺少其他东西。如果我只是 运行 LIKE %s 它确实有效,但是我需要能够像不等于一样进行搜索。

# 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%'

P.S。你也有两个占位符,但你在 execute

中只传递了一个参数

您可以将搜索词字符串包裹在&符号中,然后将其传递给 cursor.execute():

,而不是将 & 符号嵌入查询字符串中
sql = 'SELECT * from FishPond fp WHERE LOWER(fp.name) LIKE LOWER(%s)'
search_term = 'xyz'
like_pattern = '%{}%'.format(search_term)
cur.execute(sql, (like_pattern,))

为了示例的目的简化了查询。

这更加灵活,因为调用代码可以将任何有效的 LIKE 模式传递给查询。

顺便说一句:在 Postgresql 中,您可以将 ILIKE 用于 case insensitive pattern matching,因此示例查询可以这样写:

sql = 'SELECT * from FishPond fp WHERE fp.name ILIKE %s'

如文档中所述 ILIKE 是 Postgresql 扩展,而非标准 SQL。