In this example we will show how to escape the query values to prevent SQL injections in Python.
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 = %s"
capital = ("Phoenix", )
# execute a query
mycursor.execute(sql, capital)
results = mycursor.fetchall()
for row in results:
print(row)
# close the connection
mydb.close()
Output:
(2, 'Arizona', 'AZ', 'Phoenix', 113990)