如何在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 withLIKEtells 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 inputNamewith%(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 usef'{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
相关产品推荐
相关产品推荐

