Python Practice › SQLite Programs › Program 16
Search with LIKE
Write a Python program to find products whose name contains a word.
Output
[('USB cable',), ('USB hub',)]Approach
LIKE '%' || ? || '%'keeps the value as a parameter.
Solution
import sqlite3 conn = sqlite3.connect(":memory:")conn.execute("CREATE TABLE products (name TEXT)")conn.executemany("INSERT INTO products VALUES (?)", [("USB cable",), ("Wireless mouse",), ("USB hub",), ("Keyboard",)])term = "usb"print(conn.execute("SELECT name FROM products WHERE name LIKE '%' || ? || '%'", (term,)).fetchall())Output
[('USB cable',), ('USB hub',)]Line by line
Line 6
SQLite’s LIKE ignores case for English letters.
Learn the concept
New to this topic? Read the lesson, then come back.