How to Prevent SQL Injection in Update in Python MySQL


In this example, we will learn how to prevent SQL injection when updating existing records in a table in Python MySQL.

Source Code

import mysql.connector

mydb = mysql.connector.connect(
    host="localhost",
    port=3306,
    user="yourusername",
    password="yourpassword",
    db="mydatabase"
)

mycursor = mydb.cursor()

sql = "UPDATE us_state SET State_name = %s WHERE State_name = %s"
update_val = ("Ohio", "California")

mycursor.execute(sql, update_val)

mydb.commit()

print(mycursor.rowcount, "row affected")

Output:

1 row affected
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
Advertisement