First, you will have the mysql.connector
. In case you are uncertain of methods to get this setup, confer with The right way to Set up MySQL Driver in Python.
The right way to Choose from MySQL with a Filter in Python
You merely specify the WHERE
clause in your SQL assertion as follows:
import mysql.connector
mydb = mysql.connector.join(
host = "localhost",
person = "username",
password = "YoUrPaSsWoRd",
database = "your_database"
)
mycursor = mydb.cursor()
sql = "SELECT * FROM clients WHERE handle ='London Highway'"
mycursor.execute(sql)
myresult = mycursor.fetchall()
for x in myresult:
print(x)
The right way to Choose and Filter Wildcard Characters in Python
To filter wildcard characters
, you mix the WHERE
and LIKE
key phrases, and place the %
image the place the wildcards would happen.
Within the beneath instance, we are saying something that has the phrase highway
in it someplace. Word that this may exclude values that both begin or finish with highway
.
import mysql.connector
mydb = mysql.connector.join(
host = "localhost",
person = "username",
password = "YoUrPaSsWoRd",
database = "your_database"
)
mycursor = mydb.cursor()
sql = "SELECT * FROM clients WHERE handle LIKE '%highway%'"
mycursor.execute(sql)
myresult = mycursor.fetchall()
for x in myresult:
print(x)
The right way to Stop SQL Injection in your WHERE clause
As an alternative of passing dynamic values immediately into your question, somewhat move them because the second argument to the execute
command, as a set
.
import mysql.connector
mydb = mysql.connector.join(
host = "localhost",
person = "username",
password = "YoUrPaSsWoRd",
database = "your_database"
)
mycursor = mydb.cursor()
sql = "SELECT * FROM clients WHERE handle = %s"
adr = ("Maple Drive", )
mycursor.execute(sql, adr)
myresult = mycursor.fetchall()
for x in myresult:
print(x)