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