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 thecustomers
table where theaddress
column 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 to retrieve data from MySQL?
- How do I use Python to authenticate MySQL on Windows?
- How can I connect Python to a MySQL database?
- How can I use Python to interact with a MySQL database using YAML?
- How do Python MySQL and SQLite compare in terms of performance and scalability?
- How can I host a MySQL database using Python?
- How do I access MySQL using Python?
- How can I connect Python to a MySQL database using an Xserver?
- How do I connect Python with MySQL using XAMPP?
- How can I use the Python MySQL API to interact with a MySQL database?
See more codes...