Python Tutorial

Python MySQL - Update

Modify existing rows safely with a targeted WHERE clause.

UPDATE ... SET ... WHERE

UPDATE changes column values in rows matching the condition. Use parameters and commit.

import mysql.connector

conn = mysql.connector.connect(
    host="localhost", user="root", password="secret", database="mydatabase")
cursor = conn.cursor()

sql = "UPDATE customers SET address = %s WHERE address = %s"
cursor.execute(sql, ("Valley 345", "Highway 21"))
conn.commit()

print(cursor.rowcount, "record(s) affected")

Like DELETE, an UPDATE without a WHERE changes every row. Always scope it.

Update Multiple Columns

Set several columns in one statement; the parameter order matches the %s order (SET columns first, then WHERE values).

cursor.execute(
    "UPDATE customers SET name = %s, address = %s WHERE id = %s",
    ("John Smith", "New Road 1", 5))
conn.commit()

Update Using Existing Values

You can reference a column's current value — useful for counters and adjustments.

cursor.execute(
    "UPDATE products SET stock = stock - %s WHERE id = %s", (1, 42))
cursor.execute(
    "UPDATE products SET price = price * 1.10 WHERE category = %s", ("books",))
conn.commit()

Confirm the Effect

rowcount reports affected rows. Note MySQL counts a row as affected only if a value actually changed.

cursor.execute("UPDATE customers SET name = %s WHERE id = %s", ("Ann", 3))
conn.commit()
print("Rows changed:", cursor.rowcount)   # 0 if the name was already 'Ann'

Upsert: Insert or Update

To insert a row or update it if the key already exists, use ON DUPLICATE KEY UPDATE (requires a unique/primary key).

cursor.execute(
    "INSERT INTO settings (user_id, theme) VALUES (%s, %s) "
    "ON DUPLICATE KEY UPDATE theme = VALUES(theme)",
    (7, "dark"))
conn.commit()

Best Practices

  • Never run an UPDATE without a WHERE unless you mean to touch every row.
  • Preview with a matching SELECT first on important tables.
  • Wrap related updates in a transaction and rollback() on error.
  • Use ON DUPLICATE KEY UPDATE for clean insert-or-update logic.

Try It Yourself

Exercise 1: Raise every book's price by 10% in one statement.

Show solution
cursor.execute(
    "UPDATE products SET price = price * 1.10 WHERE category = %s",
    ("books",))
conn.commit()

Exercise 2: What happens if you run an UPDATE without a WHERE clause?

Show solution

Every row in the table is updated. Always scope updates with WHERE unless that is truly intended.

📘 Real-World Deep Dive

Knowing <strong>MySQL Update (MySQL)</strong> well is what turns MySQL from a curiosity into a daily tool — you'll reach for it in nearly every real project.

Real-Life Scenario

An end-to-end usage of MySQL Update that you'd actually see in a data pipeline or analytics notebook.

Real-Life Example

import mysql.connector
conn = mysql.connector.connect(database="shop")
cur = conn.cursor()
cur.execute("UPDATE users SET name = %s WHERE id = %s", ("Ada Lovelace", 1))
conn.commit(); print(cur.rowcount, "updated")

Expected Output

(see source)

Common mistakes

  • Reading with the default cursor returns tuples — switch to DictCursor for named access.
  • Strings without parameter binding produce SQL-injection holes — never use f-strings in queries.
  • Connecting through a long-lived daemon pool: make sure pool_reset_connection is on to avoid session state leakage.
  • Treating MySQL Update as a black box without reading the docs — the API has subtle defaults that bite when you scale.

🚀 Performance & Best Practices

  • Use prepared statements (cursor.executemany) for bulk inserts.
  • Fetch with cursor.fetchmany(1000) in streams instead of fetchall().
  • Use pymysql's server-side cursors for very large result sets.
  • When working with MySQL, prefer vectorised / batched operations over Python loops.

🧪 Try It Yourself

  1. Reproduce the snippet on a representative slice of your own data.
  2. Profile the snippet with cProfile or timeit and find the single biggest improvement.
  3. Generalise the snippet into a small, reusable function you can drop into future projects.

FAQ: Python MySQL - Update

Common questions about this page.

What is Python MySQL - Update?

Python MySQL - Update is a MySQL lesson that explains python mysql - update in MySQL. Modify existing rows safely with a targeted WHERE clause. Copy the samples and run them in the MySQL editor. It is written for beginners who want a clear definition and working examples.

Should I run python mysql - update examples locally for better learning?

Yes. Use the browser editor on StudyGrid for a quick check, then Download the example and run it on your computer. Local runs show real errors and the real toolchain, which is one of the fastest ways to learn python mysql - update in this MySQL MySQL lesson (Python MySQL - Update).

How do I use python mysql - update in MySQL?

To use python mysql - update in MySQL, follow the examples on this StudyGrid page. Copy a snippet, run it in the browser, then Download and run it locally for better learning. Change the values and compare the output.

What is the syntax of python mysql - update?

This Python MySQL - Update tutorial shows python mysql - update syntax with short MySQL examples. Use the code blocks in this lesson for the exact statements, then try them in your editor.

Python MySQL - Update example for beginners

Yes. This page includes a beginner python mysql - update example you can copy and run. It is designed for searches such as "python mysql - update for beginners", "python mysql - update example", and "how to use python mysql - update".

What are common mistakes with python mysql - update?

Common python mysql - update mistakes include wrong syntax, mixing types, and skipping practice. Work through this MySQL chapter in order, run every example, and check the output before moving on.

Why should I learn python mysql - update?

Python MySQL - Update is used in real MySQL work. Learning python mysql - update helps you write clearer programs and continue the MySQL tutorial on StudyGrid.

Is Python MySQL - Update free to learn online?

Yes. You can learn python mysql - update free on StudyGrid (studygrid.in). This chapter is part of the MySQL path and includes examples, syntax, and next-step links.