[파이썬] MySQL 데이터베이스 트랜잭션

MySQL is one of the most popular and widely used database management systems. It provides various features for managing data, including the concept of database transactions. In this blog post, we will explore how to work with MySQL database transactions in Python.

Understanding Database Transactions

A database transaction is a sequence of operations performed on a database that should be executed as a single logical unit of work. It allows you to ensure the atomicity, consistency, isolation, and durability of your database operations.

Working with Transactions in Python

Python provides various libraries for interacting with MySQL databases. One popular library is mysql-connector-python, which allows you to connect to a MySQL database and perform database operations using SQL queries.

To work with transactions using mysql-connector-python, follow these steps:

  1. Install the mysql-connector-python library by running the following command:
    pip install mysql-connector-python
    
  2. Import the necessary modules in your Python script:
    import mysql.connector
    from mysql.connector import Error
    
  3. Connect to your MySQL database using the connect() function:
    try:
     connection = mysql.connector.connect(
         host='your_hostname',
         database='your_database',
         user='your_username',
         password='your_password'
     )
    except Error as e:
     print(f"Error connecting to MySQL database: {e}")
    
  4. Start a new transaction using the start_transaction() method:
    try:
     connection.start_transaction()
    except Error as e:
     print(f"Error starting transaction: {e}")
    
  5. Execute your database operations within the transaction using the cursor() method:
    try:
     cursor = connection.cursor()
    
     # Execute your SQL queries here
    
     connection.commit()  # Commit the transaction if all operations are successful
    except Error as e:
     connection.rollback()  # Rollback the transaction if any operation fails
     print(f"Error executing SQL queries: {e}")
    
  6. Close the database connection once you are done:
    connection.close()
    

Example: Inserting Data in a Transaction

Let’s see an example of how to insert data into a MySQL database within a transaction using Python:

import mysql.connector
from mysql.connector import Error

try:
    connection = mysql.connector.connect(
        host='your_hostname',
        database='your_database',
        user='your_username',
        password='your_password'
    )

    connection.start_transaction()

    cursor = connection.cursor()

    # Insert multiple records into the 'users' table
    sql = "INSERT INTO users (name, email) VALUES (%s, %s)"
    values = [
        ('John Doe', 'john@example.com'),
        ('Jane Smith', 'jane@example.com'),
        ('Bob Johnson', 'bob@example.com')
    ]
    cursor.executemany(sql, values)

    connection.commit()
    print(f"Successfully inserted {cursor.rowcount} records.")

except Error as e:
    connection.rollback()
    print(f"Error executing SQL queries: {e}")

finally:
    if connection.is_connected():
        cursor.close()
        connection.close()
        print("MySQL connection closed.")

In this example, we first establish a connection to the MySQL database. Then, we start a transaction and insert multiple records into the ‘users’ table using the executemany() method. Finally, we commit the transaction and close the connection.

Conclusion

MySQL database transactions are an essential concept for ensuring data integrity and consistency. In Python, you can easily work with transactions using the mysql-connector-python library. By following the steps outlined in this blog post, you can perform database operations within a transaction, ensuring the atomicity, consistency, isolation, and durability of your changes.