In this example we will show how to select the records that start, include, or end with a given letter or phrase using the % in Python MySQL.
Source Code
import mysql.connector
# connect to server
mydb = mysql.connector.connect(
host="localhost",
port=3306,
user="yourusername",
password="yourpassword",
db="mydatabase"
)
# get a cursor
mycursor = mydb.cursor()
sql = "SELECT * FROM us_state WHERE Capital LIKE '%en%'"
# execute a query
mycursor.execute(sql)
results = mycursor.fetchall()
for row in results:
print(row)
# close the connection
mydb.close()
Output:
(2, 'Arizona', 'AZ', 'Phoenix', 113990)
(4, 'California', 'CA', 'Sacramento', 163695)
(5, 'Colorado', 'CO', 'Denver', 104094)