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

如何在Python参数化SQL查询中使用LIKE操作实现供应商名称模糊匹配

Fixing the Supplier Lookup Fuzzy Match with LIKE

Let's get your fuzzy search working so passing 'Exotic' pulls up 'Exotic Liquid'! The issue you’re hitting is almost certainly missing wildcard characters (%) in your LIKE clause—these are what tell SQL to match text before, after, or around your search term instead of requiring an exact match.

Modified Function Code

Here's the corrected version of your function:

def SupplierLookup(Name):
    cursor = conn.cursor()
    # Swap exact equality for LIKE to enable pattern matching
    SQL = '''SELECT CompanyName, ContactName, Phone FROM Supplier WHERE CompanyName LIKE ?'''
    # Wrap the input term with % wildcards to match any text before/after it
    search_term = f'%{Name}%'
    # Execute the query with the wildcard-augmented term
    for row in cursor.execute(SQL, (search_term,)).fetchall():
        # Use f-strings for cleaner, more readable output formatting
        print(f'Supplier: {row[0]} ContactPerson: {row[1]} Phone: {row[2]}')

What Changed & Why

  • LIKE Clause Instead of =: Replacing the exact match operator with LIKE tells the database to perform a pattern-based search rather than requiring perfect equality.
  • Wildcard Wrapping: The % character is SQL's standard wildcard for matching any sequence of zero or more characters. Wrapping your input Name with % (e.g., turning 'Exotic' into %Exotic%) ensures we find any supplier whose name contains 'Exotic' anywhere in it. If you only want matches that start with your input, you could use f'{Name}%' instead.
  • Cleaner Print Statement: I switched to an f-string for the output line to make the code easier to read and maintain—this is optional but a nice quality-of-life tweak.

Testing It Out

When you call SupplierLookup('Exotic'), the search_term becomes '%Exotic%', which will successfully match 'Exotic Liquid' (and any other suppliers with 'Exotic' in their name, if they exist).


内容的提问来源于stack exchange,提问作者Jebril Mohamed Ali

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 23:27:36