In this example we will show how to filter the selection using the “WHERE” statement 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 ='Denver'"
# execute a query
mycursor.execute(sql)
results = mycursor.fetchall()
for row in results:
print(row)
# close the connection
mydb.close()
Output:
(5, 'Colorado', 'CO', 'Denver', 104094)