You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中用命名参数占位符为变量加%通配符实现SQL LIKE查询

Fixing Wildcard Search with Parameterized Queries

Got it, I see where the issue is—you're not adding the % wildcards to your search value before passing it to the parameterized query. Right now, your code is doing an exact match instead of the "contains" match you want (like %this%).

Here's the correct implementation:

variable = request.form.get("input")
# Wrap the input value with % wildcards for partial matching
search_term = f"%{variable}%"
results = db.execute("SELECT * FROM table WHERE column LIKE :placeholder", {"placeholder": search_term}).fetchall()

Why this works:

  • Parameterized queries (using :placeholder here) are the safe way to handle user input, as they automatically escape special characters to prevent SQL injection.
  • By adding the % signs to the value instead of hardcoding them in the SQL string, you keep the query clean and secure.

Optional: Handling special wildcard characters

If your users might input characters that have special meaning in SQL LIKE clauses (like % or _), you can escape them first to avoid unexpected matches. For example:

def escape_like_special_chars(s):
    # Escape % and _ by prefixing them with a backslash
    return s.replace("%", "\\%").replace("_", "\\_")

variable = request.form.get("input")
escaped_variable = escape_like_special_chars(variable)
search_term = f"%{escaped_variable}%"
results = db.execute("SELECT * FROM table WHERE column LIKE :placeholder ESCAPE '\\'", {"placeholder": search_term}).fetchall()

Note that you need to add the ESCAPE '\\' clause to your SQL statement so the database knows to treat the backslash as an escape character.

内容的提问来源于stack exchange,提问作者James Langridge

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 06:36:32