Python MySQL connection.commit() Explained with Examples

The commit() method is used to save changes made to the database permanently. This is crucial when you have executed data modification queries like INSERT, UPDATE, or DELETE and want to ensure that the changes are reflected in the database.

Syntax

connection.commit()

connection: The connection object to the MySQL database.

Commit Data Update

import mysql.connector

# Establish connection to MySQL server
connection = mysql.connector.connect(
    host="localhost",
    user="root",
    password="password",
    database="mydatabase"
)

cursor = connection.cursor()

# Update a record in the 'users' table
update_query = "UPDATE users SET email = 'new_email@example.com' WHERE id = 1"
cursor.execute(update_query)

# Commit the changes to the database
connection.commit()

# Verify the update
cursor.execute("SELECT * FROM users WHERE id = 1")
updated_user = cursor.fetchone()
print("Updated User:", updated_user)

connection.close()

In this example, you can use connection.commit() to finalize changes made to the database, ensuring that modifications are effectively saved and reflected in the database.