2

我试图与LIKE LOWER('% %')命令进行模式匹配,但是我认为我在使用%s的python变量这一事实正在把它弄糟。我似乎无法找到百分比符号的任何转义字符,我的程序不会给我带来任何错误。这是问题还是有其他我缺少的东西。它确实工作,如果我只是运行LIKE %s但是我需要能够搜索不等于。如何使用与多个百分比(%)符号的PostgreSQL和Python模式匹配?

# 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 
+1

切勿使用裸露的'except:'。它会捕获所有内容,甚至是“MemoryError”。至少使用'except Exception:'。 – Bakuriu

回答

3

只传递一个参数而不是查询字符串嵌入&符号,你可以包装在&符号的搜索词串,然后传递到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模式传递给查询。

BTW:在PostgreSQL,您可以使用ILIKEcase insensitive pattern matching,这样的例子查询可以写成这样:

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

如文档ILIKE所指出的是PostgreSQL的扩展,而不是标准的SQL。

0

可以逃脱%与另一%

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

附:你也有两个占位符,但你在execute