How to Escape Query Values to Prevent SQL Injections in Python


In this example, we will learn 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)
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
Advertisement