Google News
logo
Python Program to Prevent SQL injection
To prevent SQL injection attacks in your Python program, you can use parameterized queries with placeholders instead of directly concatenating user inputs into SQL queries. Here's an example :
Program :
import mysql.connector

# Establish a connection to the database
db = mysql.connector.connect(
    host="localhost",
    user="yourusername",
    password="yourpassword",
    database="yourdatabase"
)

# Create a cursor object to execute queries
cursor = db.cursor()

# Define a parameterized query with placeholders
query = "SELECT * FROM tablename WHERE column1 = %s AND column2 = %s"

# Define the values to be inserted into the placeholders
values = ("value1", "value2")

# Execute the query with the values as a parameter
cursor.execute(query, values)

# Fetch all rows returned by the query
rows = cursor.fetchall()

# Display the rows
for row in rows:
    print(row)

# Close the database connection
db.close()
In this program, we are using parameterized queries with placeholders. The placeholders `%s` will be replaced by the values specified in the `values` variable.

When the `execute()` method is called, the query and the values are sent as separate parameters to the database, preventing any SQL injection attacks.

Note that you should always validate and sanitize user input before using it in your SQL queries, even if you are using parameterized queries.