python-mysqlHow can I use the "LIKE" operator with Python and MySQL?
The LIKE operator is used to search for a specific pattern in a column of a MySQL table using Python. It can be used in the SELECT statement to retrieve rows from a table based on a certain pattern.
Example code
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
passwd="yourpassword"
)
mycursor = mydb.cursor()
sql = "SELECT * FROM customers WHERE address LIKE '%way%'"
mycursor.execute(sql)
myresult = mycursor.fetchall()
for x in myresult:
print(x)
Output example
('John', 'Highway 21')
('Peter', 'Lowstreet 4')
('Amy', 'Apple st 652')
('Hannah', 'Mountain 21')
The code above is composed of these parts:
import mysql.connector- imports the MySQL Connector Python module which allows Python to connect to a MySQL database.mydb = mysql.connector.connect(host="localhost", user="yourusername", passwd="yourpassword")- establishes a connection to the MySQL database.mycursor = mydb.cursor()- creates a cursor object which is used to execute SQL commands.sql = "SELECT * FROM customers WHERE address LIKE '%way%'"- creates a SQL query which selects all rows from thecustomerstable where theaddresscolumn contains the patternway.mycursor.execute(sql)- executes the SQL query.myresult = mycursor.fetchall()- retrieves the results of the SQL query.for x in myresult: print(x)- prints the results of the SQL query.
Helpful links
More of Python Mysql
- How can I use Python and MySQL to generate a PDF?
- How can I create a web application using Python and MySQL?
- ¿Cómo conectar Python a MySQL usando ejemplos?
- How can I connect to MySQL using Python?
- How can I connect Python to a MySQL database?
- How do I connect Python with MySQL using XAMPP?
- How do I use Python to query MySQL with multiple conditions?
- How do I decide between using Python MySQL and PyMySQL?
- How can I use the Python MySQL API to interact with a MySQL database?
- How do I use a WHERE query in Python and MySQL?
See more codes...