- 1 1. Introduction
- 2 2. Environment Setup (Installing MariaDB & Python)
- 3 3. Connecting to MariaDB
- 4 Summary
- 5 4. Creating Databases and Tables
- 6 Summary
- 7 5. CRUD Operations (Create, Read, Update, Delete)
- 8 Summary
- 9 6. Transactions and Rollback (Ensuring Data Integrity)
- 10 요약
- 11 7. 오류 처리 (일반 오류 및 해결책)
- 12 요약
- 13 8. 결론
- 14 요약
1. Introduction
Python으로 MariaDB를 다루고 싶은 분들을 위해
많은 사람들이 Python을 사용해 MariaDB에 연결하고 데이터를 조작하고 싶어합니다. 이 글에서는 Python으로 MariaDB를 다루는 기본부터 고급 주제까지 모두 설명합니다.
다음과 같은 문제가 있나요?
- Python에서 MariaDB에 어떻게 연결해야 할지 모를 때
- Python을 이용해 MariaDB에서 데이터를 쉽게 생성, 조회, 수정, 삭제하고 싶을 때
- 흔히 발생하는 오류와 그 해결 방법을 알고 싶을 때
이 글에서 배울 내용
- Python에서 MariaDB에 손쉽게 연결하는 방법
- CRUD (Create, Read, Update, Delete) 구현 방법
- 흔히 발생하는 오류와 해결책
- 트랜잭션을 이용한 데이터 무결성 보호 방법
이 글을 읽고 나면 Python을 사용해 MariaDB를 원활히 다룰 수 있게 됩니다. 이제 자세히 살펴보겠습니다.
2. Environment Setup (Installing MariaDB & Python)
MariaDB란?
MariaDB는 MySQL의 후속으로 널리 사용되는 오픈소스 관계형 데이터베이스 관리 시스템(RDBMS)입니다. MySQL과 높은 호환성을 유지하면서도 성능이 향상되고 새로운 기능이 추가되었습니다.
필요 도구
Python에서 MariaDB를 사용하려면 다음 도구들을 준비해야 합니다:
- Python (버전 3.x 이상 권장)
- MariaDB (서버)
- MariaDB Python 커넥터 (mariadb 라이브러리)
운영체제별 MariaDB 설치 방법
Windows용
- 공식 웹사이트에서 MariaDB 설치 프로그램을 다운로드합니다.
- 설치 프로그램을 실행하고 안내에 따라 설치를 완료합니다.
- 설치가 끝난 후 다음 명령을 실행해 MariaDB가 정상 동작하는지 확인합니다:
mysql -u root -p
- 정상적으로 로그인되면 설치가 완료된 것입니다.
macOS용
macOS에서는 Homebrew를 이용해 MariaDB를 손쉽게 설치할 수 있습니다.
- Homebrew가 설치되어 있지 않다면 다음 명령으로 설치합니다:
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
- MariaDB를 설치합니다:
brew install mariadb
- MariaDB를 시작합니다:
brew services start mariadb
- 설치를 확인합니다:
mysql -u root -p
Linux (Ubuntu)용
- 패키지 목록을 업데이트하고 MariaDB를 설치합니다:
sudo apt update sudo apt install mariadb-server mariadb-client
- MariaDB를 시작합니다:
sudo systemctl start mariadb
- 부팅 시 자동으로 MariaDB가 시작되도록 설정합니다:
sudo systemctl enable mariadb
- 보안 설정 스크립트를 실행합니다:
sudo mysql_secure_installation
이를 통해 root 비밀번호를 설정하고 불필요한 기본 설정을 제거할 수 있습니다.
Python 및 필수 라이브러리 설치
Python과 MariaDB를 연동하려면 mariadb 라이브러리를 설치해야 합니다.
pip를 이용해mariadb라이브러리를 설치합니다:pip install mariadb
- 설치가 정상적으로 되었는지 확인합니다:
import mariadb print("The MariaDB library was installed successfully.")
오류가 발생하지 않으면 설치가 성공한 것입니다.
이제 Python과 MariaDB를 사용하기 위한 환경 설정이 완료되었습니다. 다음에서는 Python에서 MariaDB에 연결하는 방법을 설명하겠습니다. 
3. Connecting to MariaDB
Python으로 MariaDB에 연결하는 방법
필요한 라이브러리 임포트
MariaDB에 연결하려면 Python mariadb 라이브러리를 임포트합니다.
import mariadb
데이터베이스 연결 기본 코드
다음 코드는 Python을 사용해 MariaDB에 연결하는 기본적인 방법을 보여줍니다.
import mariadb
# Database connection settings
config = {
"host": "localhost", # Hostname of the MariaDB server
"user": "root", # MariaDB username
"password": "password", # MariaDB password
"database": "sample_db" # Database name to connect to
}
try:
# Connect to MariaDB
conn = mariadb.connect(**config)
print("Connected to MariaDB!")
# Create a cursor
cursor = conn.cursor()
# If the connection succeeds, close it
cursor.close()
conn.close()
except mariadb.Error as e:
print(f"Connection error: {e}")
About the arguments of connect()
| Argument | Description |
|---|---|
host | MariaDB server address (usually localhost) |
user | Database username |
password | Database password |
database | Database name to connect to |
If the server is remote, specify an IP address or domain name in host.
A secure connection method using environment variables
Hardcoding sensitive information such as passwords directly in your code is a security risk. By using environment variables, you can manage them more safely.
Install python-dotenv
First, install a library to manage environment variables.
pip install python-dotenv
Create a .env file and write your connection settings
Create a .env file in your project folder and add your connection settings like this:
DB_HOST=localhost
DB_USER=root
DB_PASSWORD=password
DB_NAME=sample_db
Load environment variables in your Python script
To load the .env file in a Python script, write the following:
import mariadb
import os
from dotenv import load_dotenv
# Load the .env file
load_dotenv()
config = {
"host": os.getenv("DB_HOST"),
"user": os.getenv("DB_USER"),
"password": os.getenv("DB_PASSWORD"),
"database": os.getenv("DB_NAME")
}
try:
conn = mariadb.connect(**config)
print("Connected securely to MariaDB!")
conn.close()
except mariadb.Error as e:
print(f"Connection error: {e}")
Common connection errors and how to fix them
Below are some errors you may encounter when connecting Python to MariaDB, along with their solutions.
Access denied for user 'root'@'localhost'
Error message
mariadb.OperationalError: Access denied for user 'root'@'localhost' (using password: YES)
Causes
- The user’s credentials are incorrect
- MariaDB authentication settings are not configured properly
Solutions
- Log in to MariaDB and check the user’s privileges.
mysql -u root -p
- Grant the required privileges to the user.
GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' IDENTIFIED BY 'password' WITH GRANT OPTION; FLUSH PRIVILEGES;
- Try connecting again.
Can't connect to MySQL server on 'localhost'
Error message
mariadb.OperationalError: Can't connect to MySQL server on 'localhost' (10061)
Causes
- The MariaDB server is not running
- The
hostsetting is incorrect
Solutions
- Check whether the server is running.
sudo systemctl status mariadb
- If the server is stopped, start it.
sudo systemctl start mariadb
- Check that the
hostsetting is correct.
Summary
In this section, we explained how to connect to MariaDB from Python.
- Basic connection method using
mariadb.connect() - A secure connection method using a
.envfile - Common connection errors and how to fix them
4. Creating Databases and Tables
Creating a database
In MariaDB, you need to create a database to store data. Let’s look at how to create a database using Python.
Create a database using a MariaDB management tool
You can create a database using the MariaDB command line (or GUI tools such as MySQL Workbench).
CREATE DATABASE sample_db;
To view the list of databases you created, use the following command:
SHOW DATABASES;
Create a database using Python
To create a database using Python, run the following code:
import mariadb
# Database connection (no database specified)
config = {
"host": "localhost",
"user": "root",
"password": "password"
}
try:
conn = mariadb.connect(**config)
cursor = conn.cursor()
# Create the database
cursor.execute("CREATE DATABASE IF NOT EXISTS sample_db")
print("Created database 'sample_db'.")
cursor.close()
conn.close()
except mariadb.Error as e:
print(f"Error occurred: {e}")
By adding
IF NOT EXISTS, you can prevent errors if a database with the same name already exists.
Creating a table
After creating the database, the next step is to create a table to store data.
Basic table structure
A table typically has a structure like the following:
| Column name | Data type | Description |
|---|---|---|
id | INT | User ID (auto-increment) |
name | VARCHAR(100) | User name (up to 100 characters) |
email | VARCHAR(100) UNIQUE | Email address (must be unique) |
created_at | DATETIME | Created date/time |
Create a table with SQL
If you create a table using MariaDB SQL commands, write the following:
USE sample_db;
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(100) UNIQUE NOT NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
To view the list of tables, run:
SHOW TABLES;
Create a table using Python
Here is how to create the same table using a Python script.
import mariadb
# Database connection
config = {
"host": "localhost",
"user": "root",
"password": "password",
"database": "sample_db"
}
try:
conn = mariadb.connect(**config)
cursor = conn.cursor()
# Table creation SQL
table_creation_query = """
CREATE TABLE IF NOT EXISTS users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(100) UNIQUE NOT NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
)
"""
cursor.execute(table_creation_query)
print("Created table 'users'.")
cursor.close()
conn.close()
except mariadb.Error as e:
print(f"Error occurred: {e}")
By adding
IF NOT EXISTS, you can prevent errors if the table already exists.
How to choose data types
When designing tables, it is important to choose appropriate data types. Below is a summary of commonly used data types in MariaDB.
| Data type | Use case | Example |
|---|---|---|
INT | Integer values (IDs, etc.) | 123 |
VARCHAR(n) | Variable-length strings | "Alice" |
TEXT | Long text (1,000+ characters) | "This is a long text." |
DATE | Date | 2024-02-21 |
DATETIME | Date and time | 2024-02-21 12:34:56 |
BOOLEAN | Boolean values | TRUE or FALSE |
For example, it is common to use VARCHAR(100) for the name field, but if you need a longer string, TEXT can be a good option.
How to check and drop existing tables
Check existing tables
To check the tables in a database, use the following SQL:
SHOW TABLES;
To view a table’s detailed structure, run the DESCRIBE command:
DESCRIBE users;
Drop a table
To drop a table, use DROP TABLE:
DROP TABLE users;
To drop a table from Python, run the following code:
cursor.execute("DROP TABLE IF EXISTS users")
Summary
In this section, we explained how to create databases and tables in MariaDB to store data.
- How to create a database in MariaDB
- How to create a table using Python
- How to choose appropriate data types
- How to check and drop existing tables
Now the basic setup for MariaDB is complete. In the next section, we will explain CRUD operations (Create, Read, Update, Delete) in detail.
5. CRUD Operations (Create, Read, Update, Delete)
After creating the MariaDB database and tables, the next step is to perform CRUD operations. CRUD stands for Create, Read, Update, and Delete, which are the basic operations of a database.
In this section, we will explain how to manipulate MariaDB data using Python.
Inserting data (INSERT)
To add a new record to the database, use the INSERT statement.
Insert data using SQL
To insert data using MariaDB SQL, execute the following command:
INSERT INTO users (name, email) VALUES ('Alice', 'alice@example.com');
To verify the inserted data, use the SELECT statement:
SELECT * FROM users;
Insert data using Python
To insert data using Python, run the following code:
import mariadb
# Database connection settings
config = {
"host": "localhost",
"user": "root",
"password": "password",
"database": "sample_db"
}
try:
conn = mariadb.connect(**config)
cursor = conn.cursor()
# Insert data
insert_query = "INSERT INTO users (name, email) VALUES (?, ?)"
data = ("Alice", "alice@example.com")
cursor.execute(insert_query, data)
# Save changes
conn.commit()
print("Data inserted successfully!")
cursor.close()
conn.close()
except mariadb.Error as e:
print(f"Error occurred: {e}")
Key points:
- Using
?placeholders helps prevent SQL injection.- If you do not execute
conn.commit(), the data will not be saved to the database.
Retrieving data (SELECT)
To retrieve registered data, use the SELECT statement.
Retrieve data using SQL
To retrieve data using MariaDB SQL:
SELECT * FROM users;
To retrieve data with conditions, use the WHERE clause:
SELECT * FROM users WHERE email = 'alice@example.com';
Retrieve data using Python
To retrieve data using Python, run the following code:
import mariadb
config = {
"host": "localhost",
"user": "root",
"password": "password",
"database": "sample_db"
}
try:
conn = mariadb.connect(**config)
cursor = conn.cursor()
# Retrieve data
select_query = "SELECT id, name, email FROM users"
cursor.execute(select_query)
# Display retrieved data
for (id, name, email) in cursor:
print(f"ID: {id}, Name: {name}, Email: {email}")
cursor.close()
conn.close()
except mariadb.Error as e:
print(f"Error occurred: {e}")
Key points:
- Execute SQL with
cursor.execute(select_query)and retrieve data from thecursorobject.- You can process records one by one using a
forloop.
Updating data (UPDATE)
To modify registered data, use the UPDATE statement.
Update data using SQL
To update data using MariaDB SQL, execute:
UPDATE users SET name = 'Alice Smith' WHERE email = 'alice@example.com';
Update data using Python
To update data using Python, run the following code:
import mariadb
config = {
"host": "localhost",
"user": "root",
"password": "password",
"database": "sample_db"
}
try:
conn = mariadb.connect(**config)
cursor = conn.cursor()
# Update data
update_query = "UPDATE users SET name = ? WHERE email = ?"
data = ("Alice Smith", "alice@example.com")
cursor.execute(update_query, data)
# Save changes
conn.commit()
print("Data updated successfully!")
cursor.close()
conn.close()
except mariadb.Error as e:
print(f"Error occurred: {e}")
Deleting data (DELETE)
To remove unnecessary data, use the DELETE statement.
Delete data using SQL
To delete data using MariaDB SQL, execute:
DELETE FROM users WHERE email = 'alice@example.com';
Delete data using Python
To delete data using Python, run the following code:
import mariadb
config = {
"host": "localhost",
"user": "root",
"password": "password",
"database": "sample_db"
}
try:
conn = mariadb.connect(**config)
cursor = conn.cursor()
# Delete data
delete_query = "DELETE FROM users WHERE email = ?"
data = ("alice@example.com",)
cursor.execute(delete_query, data)
# Save changes
conn.commit()
print("Data deleted successfully!")
cursor.close()
conn.close()
except mariadb.Error as e:
print(f"Error occurred: {e}")
Summary
In this section, we explained how to manipulate MariaDB data using Python.
- Insert data (INSERT)
- Retrieve data (SELECT)
- Update data (UPDATE)
- Delete data (DELETE)
You can now perform basic data operations in MariaDB using Python.
6. Transactions and Rollback (Ensuring Data Integrity)
데이터베이스 작업 시 트랜잭션을 사용하여 데이터 무결성을 유지하는 것이 중요합니다.
특히, 처리 중 오류가 발생할 때 데이터를 원래 상태로 복원(롤백)할 수 있는 기능은 일관성을 유지하는 데 필수적입니다.
이 섹션에서는 Python을 사용하여 MariaDB에서 트랜잭션을 관리하는 방법을 설명합니다.
트랜잭션이란 무엇인가?
트랜잭션은 데이터베이스 작업의 일련을 하나의 단위로 그룹화하여, 모든 프로세스가 성공하면 모든 변경 사항을 커밋하고, 오류가 발생하면 모든 변경 사항을 롤백하는 메커니즘입니다.
트랜잭션의 특성
- ACID 속성
- 원자성 : 모든 작업이 성공적으로 완료되거나, 하나도 적용되지 않습니다.
- 일관성 : 데이터 무결성이 유지됩니다.
- 격리성 : 동시 트랜잭션이 서로 간섭하지 않습니다.
- 지속성 : 커밋되면 변경 사항이 영구적으로 저장됩니다.
기본 트랜잭션 작업 (COMMIT 및 ROLLBACK)
MariaDB 트랜잭션은 다음 명령으로 제어할 수 있습니다:
| Command | Description |
|---|---|
START TRANSACTION; | Begin a transaction |
COMMIT; | Commit changes (cannot be undone after commit) |
ROLLBACK; | Cancel changes (restore the original state) |
Python에서 트랜잭션 사용
아래는 Python을 사용하여 MariaDB 트랜잭션을 관리하는 기본 예제입니다.
단일 트랜잭션 내에서 여러 작업 관리
다음 코드는 여러 삽입 작업을 하나의 트랜잭션으로 처리하고, 모든 작업이 성공할 때만 커밋합니다.
import mariadb
config = {
"host": "localhost",
"user": "root",
"password": "password",
"database": "sample_db"
}
try:
conn = mariadb.connect(**config)
cursor = conn.cursor()
# Start transaction
conn.start_transaction()
# Insert data
cursor.execute("INSERT INTO users (name, email) VALUES (?, ?)", ("Bob", "bob@example.com"))
cursor.execute("INSERT INTO users (name, email) VALUES (?, ?)", ("Charlie", "charlie@example.com"))
# Commit if all operations succeed
conn.commit()
print("Data added successfully.")
cursor.close()
conn.close()
except mariadb.Error as e:
print(f"Error occurred: {e}")
conn.rollback() # Roll back if an error occurs
핵심 포인트
conn.start_transaction()을 사용하여 트랜잭션을 시작합니다.conn.commit()을 사용하여 변경 사항을 최종화합니다 (커밋 후에는 되돌릴 수 없습니다).- 오류가 발생하면
conn.rollback()을 사용하여 변경 사항을 취소하고 원래 상태를 복원합니다.
트랜잭션 기반 오류 처리
데이터베이스 작업 중 오류가 발생할 수 있습니다.
예를 들어, 중복 이메일 주소 (UNIQUE 제약 조건 위반) 또는 서버 타임아웃이 발생할 수 있습니다.
오류 처리와 함께한 트랜잭션 관리
다음 코드는 처리 중 오류가 발생하면 변경 사항을 롤백하고 원래 상태를 복원하는 로직을 추가합니다.
import mariadb
config = {
"host": "localhost",
"user": "root",
"password": "password",
"database": "sample_db"
}
try:
conn = mariadb.connect(**config)
cursor = conn.cursor()
# Start transaction
conn.start_transaction()
try:
# First insert succeeds
cursor.execute("INSERT INTO users (name, email) VALUES (?, ?)", ("Dave", "dave@example.com"))
# Second insert causes an error (duplicate email)
cursor.execute("INSERT INTO users (name, email) VALUES (?, ?)", ("Eve", "dave@example.com"))
# Commit if all operations succeed
conn.commit()
print("Data inserted successfully.")
except mariadb.Error as e:
print(f"Error occurred during data processing: {e}")
conn.rollback() # Roll back on error
print("Transaction rolled back.")
cursor.close()
conn.close()
except mariadb.Error as e:
print(f"Database connection error: {e}")
요약
이 섹션에서는 트랜잭션의 기본 사항과 Python에서 구현하는 방법을 설명했습니다.
- 트랜잭션과 ACID 속성의 중요성
- Python에서
commit()및rollback()사용 방법 - 오류 처리와 결합된 트랜잭션 관리
7. 오류 처리 (일반 오류 및 해결책)
When working with MariaDB in Python, errors may occur.
In particular, database connection errors, SQL syntax errors, and data integrity errors are common, so it is important to understand their causes and solutions.
In this section, we introduce the causes of common errors and how to fix them.
Access denied for user (인증 오류)
오류 메시지
mariadb.OperationalError: Access denied for user 'root'@'localhost' (using password: YES)
원인
- 사용자 이름 또는 비밀번호가 올바르지 않습니다
- MariaDB 사용자가 적절한 권한을 가지고 있지 않습니다
해결책
- MariaDB에 로그인하고 사용자 권한을 확인합니다
mysql -u root -p
- 사용자에게 권한을 부여합니다
GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' IDENTIFIED BY 'password' WITH GRANT OPTION; FLUSH PRIVILEGES;
- MariaDB를 재시작합니다
sudo systemctl restart mariadb
Can't connect to MySQL server on 'localhost' (연결 오류)
오류 메시지
mariadb.OperationalError: Can't connect to MySQL server on 'localhost' (10061)
원인
- MariaDB 서버가 실행 중이 아닙니다
host설정이 올바르지 않습니다
해결책
- MariaDB 서버가 실행 중인지 확인합니다
sudo systemctl status mariadb
- 서버가 중지된 경우, 시작합니다
sudo systemctl start mariadb
- 서버가 자동으로 시작되도록 설정합니다
sudo systemctl enable mariadb
Unknown database 'sample_db' (데이터베이스가 존재하지 않음)
오류 메시지
mariadb.ProgrammingError: Unknown database 'sample_db'
원인
- 지정된 데이터베이스가 존재하지 않습니다
- 데이터베이스 이름에 오타가 있습니다
해결책
- 데이터베이스 목록을 확인합니다
SHOW DATABASES;
- 데이터베이스가 없으면 생성합니다
CREATE DATABASE sample_db;
Table doesn't exist (테이블이 존재하지 않음)
오류 메시지
mariadb.ProgrammingError: Table 'sample_db.users' doesn't exist
원인
- 지정된 테이블이 존재하지 않습니다
USE sample_db;로 데이터베이스를 선택하지 않았습니다
해결책
- 테이블 목록을 확인합니다
SHOW TABLES;
- 테이블이 없으면 생성합니다
CREATE TABLE users ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(100) NOT NULL, email VARCHAR(100) UNIQUE NOT NULL, created_at DATETIME DEFAULT CURRENT_TIMESTAMP );
Duplicate entry (중복 데이터 오류)
오류 메시지
mariadb.IntegrityError: Duplicate entry 'alice@example.com' for key 'users.email'
원인
email컬럼에UNIQUE제약이 있어 중복 값을 삽입할 수 없습니다
해결책
- 데이터를 삽입하기 전에 중복 여부를 확인합니다
ON DUPLICATE KEY UPDATE를 사용합니다
중복을 방지하는 Python 코드
try:
cursor.execute("INSERT INTO users (name, email) VALUES (?, ?)", ("Alice", "alice@example.com"))
conn.commit()
except mariadb.IntegrityError:
print("Error: The email address already exists.")
또는 ON DUPLICATE KEY UPDATE 사용
INSERT INTO users (name, email) VALUES ('Alice', 'alice@example.com')
ON DUPLICATE KEY UPDATE name = 'Alice Updated';
Incorrect number of bindings (파라미터 수 불일치)
오류 메시지
mariadb.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 2, and there are 1 supplied.
원인
- SQL 문에 필요한 파라미터 수와 제공된 인수 수가 일치하지 않습니다
해결책
- 플레이스홀더 수가 파라미터 수와 일치하는지 확인합니다
잘못된 코드
cursor.execute("INSERT INTO users (name, email) VALUES (?, ?)", ("Alice"))
정답 코드
cursor.execute("INSERT INTO users (name, email) VALUES (?, ?)", ("Alice", "alice@example.com"))
요약
이 섹션에서는 Python에서 MariaDB를 사용할 때 발생하는 일반적인 오류와 해결 방법을 설명했습니다.
Access denied for user(인증 오류)Can't connect to MySQL server(연결 오류)Unknown database(데이터베이스가 존재하지 않음)Table doesn't exist(테이블이 존재하지 않음)Duplicate entry(중복 데이터 오류)Incorrect number of bindings(파라미터 개수 불일치)
8. 결론
이 글에서는 Python을 사용한 MariaDB 활용 방법을 기본 개념부터 고급 주제까지 설명했습니다.
기본적인 데이터베이스 작업을 이해하고 오류 처리와 트랜잭션 관리를 올바르게 구현함으로써 보다 안전하고 효율적인 데이터 작업을 수행할 수 있습니다.
기사 요약
환경 설정
- MariaDB 설치 방법 (Windows / Mac / Linux)
- Python용 MariaDB 커넥터 라이브러리 (mariadb) 설치 방법
MariaDB 연결
- 기본 데이터베이스 연결 방법
- 환경 변수를 이용한 보안 연결
- 일반적인 연결 오류에 대한 해결책
데이터베이스 및 테이블 생성
- 데이터베이스 생성 (SQL / Python)
- 테이블 생성 및 데이터 타입 선택
- 기존 테이블 확인 및 삭제
CRUD 작업 (Create, Read, Update, Delete)
- Python을 이용한 기본 데이터 작업
- SQL 인젝션 방지를 위한 플레이스홀더 사용
- 적절한 오류 처리
트랜잭션 및 롤백
- 트랜잭션의 중요성 (ACID 특성)
- 오류 발생 시 데이터 복구 (롤백)
- AutoCommit을 비활성화하여 수동으로 트랜잭션 관리
오류 처리 (일반 오류 및 해결책)
- 인증 오류 (
Access denied for user) - 연결 오류 (
Can't connect to MySQL server) - 데이터베이스 또는 테이블을 찾을 수 없는 오류
- 중복 데이터 오류 (
Duplicate entry) - 데드락 처리 및 재시도 로직 구현
Python과 MariaDB를 결합할 때의 핵심 포인트
- 플레이스홀더 사용
cursor.execute("INSERT INTO users (name, email) VALUES (?, ?)", ("Alice", "alice@example.com"))
→ SQL 문에 직접 값을 삽입하는 대신 바인드 변수를 사용하여 SQL 인젝션을 방지합니다.
트랜잭션을 적절히 관리
conn.commit()을 사용해 변경 사항을 명시적으로 커밋합니다.
오류 발생 시conn.rollback()을 호출해 데이터 무결성을 유지합니다.철저한 오류 처리 구현
try-except블록을 사용해 잠재적인 오류를 사전에 포착합니다.
OperationalError,IntegrityError와 같은 오류에 대한 구체적인 처리 전략을 준비합니다.성능 고려
대량 삽입 (한 번에 여러 레코드 삽입)
적절한 인덱싱 (검색 성능 향상)
추가 학습을 위한 자료
Python과 MariaDB 통합에 대한 이해를 심화하고 싶다면 다음 자료를 참고하세요:
공식 문서
관련 학습 콘텐츠
추천 도서
- SQL, 2nd Edition: Database Operations from Scratch – SQL 기본을 철저히 학습
- Effective Python: 90 Specific Ways to Improve Your Python Programs – Python 베스트 프랙티스 습득
요약
MariaDB와 Python을 통합하면 스크립트 기반 데이터 관리와 자동화가 가능해집니다.
기본 CRUD 작업뿐 아니라 적절한 오류 처리와 트랜잭션 관리를 구현함으로써 보다 안전하고 효율적인 시스템을 구축할 수 있습니다.
다음 단계로, 효율적인 데이터 관리와 API 통합에 대해 배우고 이를 실제 데이터베이스 작업에 적용해 보세요.


