First, you will need the mysql.connector
. If you are unsure of how to get this setup, refer to How to Install MySQL Driver in Python
.
How to Select from MySQL with a Filter in Python
You simply specify the WHERE
clause in your SQL statement as follows:
import mysql.connector
mydb = mysql.connector.connect(
host = "localhost",
user = "username",
password = "YoUrPaSsWoRd",
database = "your_database"
)
mycursor = mydb.cursor()
sql = "SELECT * FROM customers WHERE address ='London Road'"
mycursor.execute(sql)
myresult = mycursor.fetchall()
for x in myresult:
print(x)
How to Select and Filter Wildcard Characters in Python
To filter wildcard characters
, you combine the WHERE
and LIKE
keywords, and place the %
symbol where the wildcards would occur.
In the below example, we say anything that has the word road
in it somewhere. Note that this will exclude values that either start or end with road
.
import mysql.connector
mydb = mysql.connector.connect(
host = "localhost",
user = "username",
password = "YoUrPaSsWoRd",
database = "your_database"
)
mycursor = mydb.cursor()
sql = "SELECT * FROM customers WHERE address LIKE '%road%'"
mycursor.execute(sql)
myresult = mycursor.fetchall()
for x in myresult:
print(x)
How to Prevent SQL Injection in your WHERE clause
Instead of passing dynamic values directly into your query, rather pass them as the second argument to the execute
command, as a set
.
import mysql.connector
mydb = mysql.connector.connect(
host = "localhost",
user = "username",
password = "YoUrPaSsWoRd",
database = "your_database"
)
mycursor = mydb.cursor()
sql = "SELECT * FROM customers WHERE address = %s"
adr = ("Maple Drive", )
mycursor.execute(sql, adr)
myresult = mycursor.fetchall()
for x in myresult:
print(x)