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 do I connect Python with MySQL using XAMPP?
- How can I use Python and MySQL to generate a PDF?
- How can I connect Python to a MySQL database?
- How can I use Yum to install the MySQLdb Python module?
- How do I use Python to authenticate MySQL on Windows?
- How do I use Python to show the MySQL processlist?
- How can I use Python to retrieve data from MySQL?
- How can I use Python to interact with a MySQL database using YAML?
- How do I use Python to connect to a MySQL database using XAMPP?
- How to compile a MySQL-Python application for x86_64-Linux-GNU-GCC?
See more codes...