我試圖與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
切勿使用裸露的'except:'。它會捕獲所有內容,甚至是「MemoryError」。至少使用'except Exception:'。 – Bakuriu