Python MySQL Operations with Parameterized Queries
This Python script demonstrates how to perform MySQL operations (Insert, Update, Delete)
using parameterized queries with the %s placeholder to prevent SQL injection.
The script connects to a MySQL database and performs the following:
1. **Insert Operation**: Inserts a new student's data into the `students` table.
2. **Update Operation**: Updates the student's age in the table.
3. **Delete Operation**: Deletes the student's record from the table.
Here is the Python script with user input and parameterized queries using `%s`:
```python
import mysql.connector
# Establish connection to the MySQL server
conn = mysql.connector.connect(
host="localhost", # or your host
user="root", # your MySQL username
password="", # your MySQL password
database="testdb" # the database name
# Create a cursor object to interact with the database
cursor = conn.cursor()
# Insert operation with user input using %s for parameterized query
def insert_data():
name = input("Enter the student's name: ")
age = input("Enter the student's age: ")
sql_insert = "INSERT INTO students (name, age) VALUES (%s, %s)"
cursor.execute(sql_insert, (name, age))
conn.commit()
print(f"Data inserted for {name} successfully!")
# Update operation with user input using %s for parameterized query
def update_data():
name = input("Enter the student's name to update: ")
new_age = input(f"Enter the new age for {name}: ")
sql_update = "UPDATE students SET age = %s WHERE name = %s"
cursor.execute(sql_update, (new_age, name))
conn.commit()
print(f"Data updated for {name} successfully!")
# Delete operation with user input using %s for parameterized query
def delete_data():
name = input("Enter the student's name to delete: ")
sql_delete = "DELETE FROM students WHERE name = %s"
cursor.execute(sql_delete, (name,))
conn.commit()
print(f"Data deleted for {name} successfully!")
# Menu to perform operations
def main():
while True:
print("\nChoose an operation:")
print("1. Insert data")
print("2. Update data")
print("3. Delete data")
print("4. Exit")
choice = input("Enter your choice: ")
if choice == "1":
insert_data()
elif choice == "2":
update_data()
elif choice == "3":
delete_data()
elif choice == "4":
break
else:
print("Invalid choice. Please try again.")
cursor.close()
conn.close()
# Run the program
if __name__ == "__main__":
main()
```
In this script:
- **Parameterized Queries**: The use of `%s` placeholders ensures that user input is safely
handled, preventing SQL injection.
You can run this Python script after installing `mysql-connector-python` using the command:
`pip install mysql-connector-python`
It will allow the user to choose operations such as Insert, Update, and Delete from the menu.