How to Perform Fuzzy Searches in MySQL with Python’s PyMySQL and mysql‑connector
This guide demonstrates how to install PyMySQL or mysql‑connector‑python, connect to a MySQL database from Python, execute LIKE‑based fuzzy queries, handle results, and safely close resources, with detailed code examples and practical tips.
Method 1: Using the PyMySQL library
When performing fuzzy queries in MySQL from Python, you typically use the pymysql or mysql-connector-python libraries to connect and execute queries. The following example shows how to install PyMySQL, connect, run a LIKE query, and process results.
1.1 Install PyMySQL
First ensure the pymysql package is installed; if not, install it via pip:
pip install pymysql1.2 Write Python code for fuzzy query
import pymysql
# Database connection configuration
config = {
'host': 'localhost',
'user': 'your_username',
'password': 'your_password',
'database': 'your_database',
'charset': 'utf8mb4',
'cursorclass': pymysql.cursors.DictCursor
}
# Connect to the database
connection = pymysql.connect(**config)
try:
with connection.cursor() as cursor:
# Use LIKE for fuzzy matching; % is the wildcard
sql = "SELECT * FROM articles WHERE content LIKE %s"
search_term = '%Python%'
cursor.execute(sql, (search_term,))
results = cursor.fetchall()
for row in results:
print(f"ID: {row['id']}, Title: {row['title']}, Content: {row['content'][:50]}...")
finally:
connection.close()1.3 Notes
Replace your_username, your_password, and your_database with your actual credentials.
Use % as the wildcard in LIKE; you can adjust the pattern (e.g., Python% or %Python) to match prefixes or suffixes.
The parameter must be passed as a single‑element tuple, e.g., (search_term,).
Use fetchall() to retrieve all rows; fetchone() or fetchmany(size) can retrieve partial results.
A try...finally block ensures the connection is closed even if an error occurs.
Method 2: Using the mysql‑connector‑python library
The official MySQL connector for Python can also perform fuzzy queries. Install it via pip if needed.
2.1 Install mysql-connector-python
pip install mysql-connector-python2.2 Write Python code for fuzzy query
import mysql.connector
# Database connection configuration
config = {
'host': 'localhost',
'user': 'your_username',
'password': 'your_password',
'database': 'your_database'
}
# Connect to the database
cnx = mysql.connector.connect(**config)
try:
cursor = cnx.cursor(dictionary=True)
query = "SELECT * FROM articles WHERE content LIKE %s"
search_term = '%Python%'
cursor.execute(query, (search_term,))
results = cursor.fetchall()
for row in results:
print(f"ID: {row['id']}, Title: {row['title']}, Content: {row['content'][:50]}...")
finally:
if cursor:
cursor.close()
if cnx.is_connected():
cnx.close()2.3 Notes
Replace the placeholder credentials with your actual MySQL credentials.
The connector’s default settings usually suffice; you can add charset or cursor options if needed.
Close both cursor and connection to release resources.
Using a context manager ( with) can automate cleanup, but the example shows explicit closing.
Always use parameterized queries to avoid SQL injection.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
