How to Use Python MySQL Update Query – Step-by-Step Guide
When working with databases in your website or app, it's common to update existing records — like changing a user’s email address or updating order status. Python, when used with MySQL, makes this process simple and efficient using the UPDATE
query.
In this article, you’ll learn how to:
- Connect Python to a MySQL database
- Write and execute an
UPDATE
query
- Handle responses and exceptions
Let’s dive in!
Prerequisites
Before you begin, make sure you have:
- Python installed
- MySQL Server running
mysql-connector-python
installed
You can install the MySQL connector with:
pip install mysql-connector-python
Step 1: Connect to MySQL Database
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="your_username",
password="your_password",
database="your_database"
)
This code sets up a connection to your MySQL database. Replace the values with your actual credentials.
Step 2: Write the Update Query
Let’s say you want to update a user’s email where the id
is 1:
mycursor = mydb.cursor()
sql = "UPDATE users SET email = %s WHERE id = %s"
val = ("newemail@example.com", 1)
mycursor.execute(sql, val)
mydb.commit()
print(mycursor.rowcount, "record(s) updated")
Explanation:
UPDATE users
– This targets the users
table.
SET email = %s
– We’re updating the email
column.
WHERE id = %s
– Ensures only the row with id = 1
is updated.
execute(sql, val)
– Safely executes the query with parameters.
commit()
– Saves changes to the database.
Step 3: Add Error Handling (Optional but Recommended)
try:
mycursor = mydb.cursor()
sql = "UPDATE users SET email = %s WHERE id = %s"
val = ("newemail@example.com", 1)
mycursor.execute(sql, val)
mydb.commit()
print(mycursor.rowcount, "record(s) updated successfully")
except mysql.connector.Error as err:
print("Error:", err)
finally:
mydb.close()
Adding try-except-finally
ensures your app doesn’t crash if something goes wrong.
Real-World Example Use Cases
- Update user profiles
- Change product prices
- Modify order statuses
- Reset passwords
Final Tips
- Always use placeholders (
%s
) to avoid SQL injection.
- Call
.commit()
after any change (INSERT/UPDATE/DELETE).
- Use
.rowcount
to know how many rows were affected.