In Python's `mysql.connector`, `autocommit` is `False` by default, so Data Manipulation Language (DML) commands like `INSERT`, `UPDATE`, and `DELETE` run inside an uncommitted transaction until you explicitly call `con.commit()`. Notice that `commit()` and `rollback()` are methods on the connection object (`con`), not on the cursor (`cur`). If an error occurs midway through a multi-step update, calling `con.rollback()` reverts uncommitted changes and preserves table consistency.
- 1. Why DML Commands Require con.commit() to Persist Changes
- 2. Inserting Single and Multiple Rows Using execute() and executemany()
- 3. Updating Filtered Records Safely and Handling Rollback on Errors
- 4. Insert Multiple Records, Update Price, and Commit Safely in Python
- 5. Transaction Control and DML Behavior in mysql.connector
- 6. Common Mistakes & Top Scorer Tips
- 7. Interactive Concept Check Quiz
- 8. Frequently Asked Questions
1. Why DML Commands Require con.commit() to Persist Changes
Unlike the MySQL interactive command-line client—where `autocommit` is enabled by default—`mysql.connector` disables `autocommit` when opening a Python connection. Consequently, when you run `cur.execute("INSERT INTO ...")` or `cur.execute("UPDATE ...")`, MySQL writes the change into a temporary transaction buffer visible only to your current session. If you inspect the table from MySQL Workbench or close your Python script without calling `con.commit()`, the new or modified rows vanish silently as MySQL rolls back the open transaction on disconnect. This explains a classic CBSE lab mistake: the Python script prints `'Record inserted'` without errors, yet `SELECT *` in MySQL shows zero new rows. Always invoke `con.commit()` on the connection object immediately after verifying that your DML statement—or logical group of DML statements—succeeded cleanly.
- `commit()` belongs to the connection (`con.commit()`), never the cursor (`cur.commit()` raises `AttributeError`).
- DDL commands (`CREATE`, `ALTER`, `DROP`, `TRUNCATE`) trigger an implicit commit in MySQL automatically.
- Pass `autocommit=True` inside `connect()` only if every single DML call should persist immediately without rollback control.
2. Inserting Single and Multiple Rows Using execute() and executemany()
To insert a single record cleanly, prepare an `INSERT INTO table(col1, col2, col3) VALUES (%s, %s, %s)` template and pass the column values as a tuple to `cur.execute(sql, data)`. Specifying the column list explicitly protects your code against schema column-order changes and lets `AUTO_INCREMENT` primary keys populate automatically. When inserting a batch of records—such as five new inventory products—calling `cur.executemany(sql, list_of_tuples)` sends the batch efficiently in one round trip instead of looping `execute()` manually. After `execute()` or `executemany()`, inspect `cur.rowcount` to verify how many rows were inserted, and read `cur.lastrowid` if you need the generated `AUTO_INCREMENT` ID for a child table. Finally, call `con.commit()` once after the batch completes so all inserted rows become permanent atomically.
- `executemany(sql, rows_list)` accepts a list of tuples and runs bulk inserts cleanly.
- Always include explicit column names in `INSERT INTO` when tables contain default or `AUTO_INCREMENT` columns.
- Check `cur.rowcount` right after `executemany()` to confirm the exact count of inserted rows.
3. Updating Filtered Records Safely and Handling Rollback on Errors
An `UPDATE` statement modifies existing rows, so pairing it with a precise `WHERE` clause and `con.commit()` is mandatory to avoid corrupting the entire table. Write `UPDATE products SET price = price * 1.10 WHERE category = %s` and check `cur.rowcount` before committing to confirm whether any matching rows actually changed—MySQL counts only rows whose column values physically differed or matched depending on client flags. For multi-step operations, such as deducting stock from one warehouse row and adding it to another, place both `execute()` calls inside a `try` block, call `con.commit()` only after both succeed, and call `con.rollback()` inside the `except` block. If the second query violates a `CHECK` or `PRIMARY KEY` constraint, `rollback()` undoes the first deduction cleanly so inventory totals remain balanced.
- Never omit the `WHERE` clause in `UPDATE` unless you intentionally intend to modify every row.
- Pair `try: ... con.commit()` with `except: con.rollback()` for atomic multi-table updates.
- When `cur.rowcount == 0` after `UPDATE`, inform the user that no matching record required updating.
4. Insert Multiple Records, Update Price, and Commit Safely in Python
con = None
cur = None
try:
import mysql.connector as mc
con = mc.connect(
host="localhost",
user="root",
password="secret_password",
database="store_db",
)
cur = con.cursor()
insert_sql = "INSERT INTO items (item_id, item_name, price) VALUES (%s, %s, %s)"
new_items = [
(101, "Geometry Box", 140),
(102, "Graph Pad", 75),
]
cur.executemany(insert_sql, new_items)
print("Inserted rows:", cur.rowcount)
update_sql = "UPDATE items SET price = price + %s WHERE item_id = %s"
cur.execute(update_sql, (20, 101))
print("Updated rows:", cur.rowcount)
con.commit()
print("Transaction committed successfully.")
except Exception as err:
if con is not None and con.is_connected():
con.rollback()
print("Transaction rolled back:", err)
finally:
if cur is not None:
cur.close()
if con is not None and con.is_connected():
con.close()
Verified Console / Dry-Run Output:
Inserted rows: 2
Updated rows: 1
Transaction committed successfully.
5. Transaction Control and DML Behavior in mysql.connector
| Operation | Object Used | Auto-Committed? | Key Behavior |
|---|---|---|---|
| INSERT INTO ... VALUES (...) | Cursor (execute / executemany) | No (default False) | Buffered in transaction until con.commit() |
| UPDATE ... SET ... WHERE ... | Cursor (execute) | No (default False) | Modifies matched rows; sets cur.rowcount |
| con.commit() | Connection object | Persists changes | Makes all pending DML writes permanent |
| con.rollback() | Connection object | Reverts changes | Undoes uncommitted DML since last commit |
| CREATE / DROP / ALTER TABLE | Cursor (execute) | Yes (implicit) | MySQL auto-commits DDL statements |
Build Bug-Free Python-MySQL DML Projects
Book a free 1:1 session at 4Achievers Junior (Grades 3-12, 1-on-1 & 1:4 Micro-Pods) to practice `INSERT`, `UPDATE`, and `commit()` for CBSE CS 083.
6. Common Mistakes & Top Scorer Tips
- Avoid Mistake: Calling `cur.commit()` on the cursor object instead of `con.commit()` on the connection object.
- Avoid Mistake: Forgetting `con.commit()` after `INSERT` or `UPDATE`, causing changes to disappear as soon as the script exits.
- Avoid Mistake: Using `con.commit()` inside a loop for every single row instead of once after `executemany()`, slowing down bulk inserts.
- Avoid Mistake: Updating records without a `WHERE` condition, unintentionally overwriting every row in the table.
- Examiner / Mentor Tip: Board marking schemes award 1 dedicated mark for `con.commit()` in `INSERT`/`UPDATE`/`DELETE` programming questions.
- Examiner / Mentor Tip: If asked why `SELECT` does not need `commit()`, explain that `SELECT` is a read-only DQL command that makes no data changes.
- Examiner / Mentor Tip: Know `executemany()` syntax: it takes one SQL string and a list of parameter tuples.
7. Interactive Concept Check Quiz
Question: Which statement correctly saves an `UPDATE` query executed through cursor `cur` on connection `conn`?
8. Frequently Asked Questions
Do I need to call `con.commit()` after running a `SELECT` query?
What happens if my Python program crashes before `con.commit()` is reached?
How do I turn on automatic commits if needed?
Explore Related Lessons & Free Interactive Tools
- All 110 Guides in CBSE CS (083) & IP (065) Hub
- Safe Parameterized Queries Using the %s Placeholder in Python
- SQL String Functions: LEFT(), RIGHT(), MID(), and SUBSTR()
- SQL String Functions: INSTR(), LENGTH(), TRIM(), UCASE() & LCASE()
- Interactive Tool: CBSE CS 083 Python Output Predictor Quiz
- Interactive Tool: CBSE SQL GROUP BY / HAVING / JOIN Query Evaluator
