我试图与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