Of course! Here is a comprehensive guide on how to update data in a MySQL database using Python, covering the best practices, security, and common scenarios.

We will use the mysql-connector-python library, which is the official driver from Oracle. The principles shown here are also applicable to other libraries like PyMySQL.
Prerequisites
Before you start, make sure you have:
-
Python installed on your system.
-
A MySQL server running and accessible.
(图片来源网络,侵删) -
A database and table to work with. Let's use this example for our code samples:
-- Create a database (if it doesn't exist) CREATE DATABASE IF NOT EXISTS company_db; -- Use the database USE company_db; -- Create an 'employees' table CREATE TABLE IF NOT EXISTS employees ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(100) NOT NULL, department VARCHAR(100), salary DECIMAL(10, 2) ); -- Insert some sample data INSERT INTO employees (name, department, salary) VALUES ('Alice', 'Engineering', 90000.00), ('Bob', 'Marketing', 65000.00), ('Charlie', 'Engineering', 110000.00); -
Install the MySQL Connector library:
pip install mysql-connector-python
The Basic UPDATE Statement in Python
The core idea is to:
- Establish a connection to the database.
- Create a cursor object.
- Execute an
UPDATESQL query. - Commit the transaction to save the changes.
- Close the cursor and connection.
Here is a basic, functional example.

import mysql.connector
from mysql.connector import Error
def update_employee_salary(employee_id, new_salary):
"""Updates the salary of a specific employee."""
connection = None
cursor = None
try:
# Establish the database connection
# Replace with your actual database credentials
connection = mysql.connector.connect(
host='localhost',
database='company_db',
user='your_username',
password='your_password'
)
if connection.is_connected():
cursor = connection.cursor()
# --- The SQL UPDATE statement ---
# Use a WHERE clause to specify which row(s) to update.
# Omitting the WHERE clause will update ALL rows!
sql_update_query = "UPDATE employees SET salary = %s WHERE id = %s"
# Data to be updated
data = (new_salary, employee_id)
# Execute the query
cursor.execute(sql_update_query, data)
# Commit the transaction to make the change permanent
connection.commit()
print(f"{cursor.rowcount} record(s) updated successfully.")
except Error as e:
print(f"Error while connecting to MySQL or updating data: {e}")
finally:
# Closing the cursor and connection
if connection and connection.is_connected():
if cursor:
cursor.close()
connection.close()
print("MySQL connection is closed.")
# --- Example Usage ---
# Update Bob's salary (he has id = 2)
update_employee_salary(employee_id=2, new_salary=70000.00)
Explanation of Key Parts:
sql_update_query = "UPDATE employees SET salary = %s WHERE id = %s": This is the SQL query.UPDATE employees: Specifies the table to modify.SET salary = %s: Specifies the column to change and its new value. We use a placeholder%s.WHERE id = %s: This is critical. It ensures that only the row with the matchingidis updated. If you forget this, you will update every employee's salary to the new value!
data = (new_salary, employee_id): This is a tuple containing the values for the placeholders. The order must match the order of the%splaceholders in the query.cursor.execute(sql_update_query, data): This safely executes the query. The library handles the proper escaping of the data, preventing SQL injection.connection.commit(): This is a crucial step. In database transactions, changes are made in a temporary state.commit()makes the change permanent. If you were to roll back the transaction, the change would be discarded.cursor.rowcount: This attribute tells you how many rows were affected by the lastexecute()statement. It's useful for confirming that yourWHEREclause matched a record.
Security: Preventing SQL Injection
Never format your queries by directly inserting variables into the string, like this:
# ❌ DANGEROUS - DO NOT DO THIS!
sql_query = f"UPDATE employees SET salary = {new_salary} WHERE id = {employee_id}"
cursor.execute(sql_query)
This makes your application vulnerable to SQL Injection attacks. The %s placeholder method is the standard, secure way to pass data to a query. The MySQL connector automatically sanitizes the input data.
Updating Multiple Columns
To update multiple columns, simply add them to the SET clause.
def update_employee_details(employee_id, new_name, new_department):
"""Updates the name and department of an employee."""
connection = None
cursor = None
try:
connection = mysql.connector.connect(
host='localhost',
database='company_db',
user='your_username',
password='your_password'
)
if connection.is_connected():
cursor = connection.cursor()
# SQL query to update multiple columns
sql_update_query = "UPDATE employees SET name = %s, department = %s WHERE id = %s"
# Data tuple with values in the correct order
data = (new_name, new_department, employee_id)
cursor.execute(sql_update_query, data)
connection.commit()
print(f"{cursor.rowcount} record(s) updated successfully.")
except Error as e:
print(f"Error: {e}")
finally:
if connection and connection.is_connected():
if cursor:
cursor.close()
connection.close()
print("MySQL connection is closed.")
# --- Example Usage ---
# Update Charlie's name and department
update_employee_details(employee_id=3, new_name='Charles', new_department='Product')
Best Practice: Using a Context Manager (with statement)
Manually opening and closing connections and cursors can be tedious and error-prone. A better way is to use a context manager, which handles cleanup automatically.
Here is a more robust and reusable function using a with statement.
import mysql.connector
from mysql.connector import Error
def update_record_with_context_manager():
"""A more robust way to handle database connections."""
# Configuration dictionary for better readability
db_config = {
'host': 'localhost',
'database': 'company_db',
'user': 'your_username',
'password': 'your_password'
}
update_query = "UPDATE employees SET salary = %s WHERE name = %s"
data_to_update = (95000.00, 'Alice') # Update Alice's salary
try:
# The 'with' statement ensures the connection is closed automatically
with mysql.connector.connect(**db_config) as connection:
if connection.is_connected():
with connection.cursor() as cursor:
cursor.execute(update_query, data_to_update)
connection.commit()
print(f"{cursor.rowcount} record(s) updated successfully.")
except Error as e:
print(f"Error while connecting to MySQL: {e}")
# --- Example Usage ---
update_record_with_context_manager()
Why this is better:
- Automatic Resource Management: The
withstatement guarantees thatconnection.close()andcursor.close()are called, even if errors occur. - Cleaner Code: It reduces the amount of boilerplate
try...finallycode. - Readability: Separating the configuration into a dictionary makes the code cleaner and easier to manage.
Summary of Best Practices
- Always use placeholders (
%s) for your data to prevent SQL injection. - Always use a
WHEREclause in yourUPDATEstatement unless you intentionally want to update every row. - Always
commit()your transaction to save the changes to the database. - Always close your connections using
try...finallyblocks or, preferably,withstatements. - Handle exceptions gracefully to avoid your program crashing due to database errors.
- Check
cursor.rowcountto verify that your update affected the expected number of rows. If it's0, it means yourWHEREclause didn't match any records.
