jos*_*non 2 python postgresql mysql-real-escape-string pattern-matching sql-like
我正在尝试与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
Run Code Online (Sandbox Code Playgroud)
您可以将搜索词字符串包装在与号中,而不是将与号嵌入查询字符串中,然后将其传递给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,))
Run Code Online (Sandbox Code Playgroud)
出于示例的目的简化了查询。
这更加灵活,因为调用代码可以将任何有效的 LIKE 模式传递给查询。
BTW:在PostgreSQL,您可以使用ILIKE为不区分大小写的模式匹配,这样的例子查询可以写成这样:
sql = 'SELECT * from FishPond fp WHERE fp.name ILIKE %s'
Run Code Online (Sandbox Code Playgroud)
如文档中所述,ILIKE是 Postgresql 扩展,而不是标准 SQL。
| 归档时间: |
|
| 查看次数: |
3273 次 |
| 最近记录: |