บทเรียน Python MariaDB: การเชื่อมต่อ, CRUD, ธุรกรรม, และการจัดการข้อผิดพลาด

目次

1. บทนำ

สำหรับผู้ที่ต้องการทำงานกับ MariaDB ด้วย Python

หลายคนต้องการเชื่อมต่อกับ MariaDB ด้วย Python และจัดการข้อมูล ในบทความนี้เราจะอธิบายทุกอย่างตั้งแต่พื้นฐานจนถึงหัวข้อขั้นสูงสำหรับการทำงานกับ MariaDB ด้วย Python

คุณมีปัญหาเหล่านี้หรือไม่?

  • คุณไม่รู้วิธีเชื่อมต่อกับ MariaDB จาก Python
  • คุณต้องการสร้าง อ่าน ปรับปรุง และลบข้อมูลใน MariaDB ด้วย Python อย่างง่าย
  • คุณต้องการเรียนรู้เกี่ยวกับข้อผิดพลาดทั่วไปและวิธีแก้ไข

สิ่งที่คุณจะได้เรียนรู้ในบทความนี้

  • วิธีเชื่อมต่อกับ MariaDB จาก Python อย่างง่าย
  • วิธีทำ CRUD (Create, Read, Update, Delete)
  • ข้อผิดพลาดทั่วไปและวิธีแก้ไข
  • วิธีปกป้องความสมบูรณ์ของข้อมูลด้วย transaction

หลังจากอ่านบทความนี้แล้ว คุณจะสามารถทำงานกับ MariaDB ด้วย Python ได้อย่างราบรื่น ตอนนี้มาดำดิ่งสู่รายละเอียดกันเลย

2. การตั้งค่าสภาพแวดล้อม (การติดตั้ง MariaDB & Python)

MariaDB คืออะไร?

MariaDB เป็นระบบจัดการฐานข้อมูลเชิงสัมพันธ์แบบโอเพ่นซอร์ส (RDBMS) ที่ได้รับความนิยมเป็นตัวสืบทอดจาก MySQL แม้จะรักษาความเข้ากันได้สูงกับ MySQL แต่ MariaDB มีประสิทธิภาพที่ดีขึ้นและเพิ่มฟีเจอร์ใหม่ ๆ

เครื่องมือที่จำเป็น

เพื่อทำงานกับ MariaDB ใน Python คุณต้องเตรียมเครื่องมือดังต่อไปนี้:

  • Python (แนะนำเวอร์ชัน 3.x หรือใหม่กว่า)
  • MariaDB (เซิร์ฟเวอร์)
  • MariaDB Python connector (ไลบรารี mariadb)

วิธีติดตั้ง MariaDB (ตามระบบปฏิบัติการ)

สำหรับ Windows

  1. ดาวน์โหลดตัวติดตั้ง MariaDB จาก เว็บไซต์ทางการ .
  2. รันตัวติดตั้งและทำตามคำแนะนำเพื่อเสร็จสิ้นการติดตั้ง
  3. หลังการติดตั้ง ให้ตรวจสอบว่า MariaDB ทำงานโดยรันคำสั่งต่อไปนี้:
    mysql -u root -p
    
  1. หากคุณสามารถล็อกอินได้สำเร็จ การติดตั้งก็เสร็จสมบูรณ์

สำหรับ Mac

บน Mac คุณสามารถติดตั้ง MariaDB ได้อย่างง่ายดายโดยใช้ Homebrew.

  1. หากยังไม่มี Homebrew ให้ติดตั้งด้วยคำสั่งต่อไปนี้:
    /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
    
  1. ติดตั้ง MariaDB:
    brew install mariadb
    
  1. เริ่ม MariaDB:
    brew services start mariadb
    
  1. ตรวจสอบการติดตั้ง:
    mysql -u root -p
    

สำหรับ Linux (Ubuntu)

  1. อัปเดตรายการแพ็กเกจและติดตั้ง MariaDB:
    sudo apt update
    sudo apt install mariadb-server mariadb-client
    
  1. เริ่ม MariaDB:
    sudo systemctl start mariadb
    
  1. เปิดใช้งาน MariaDB (ให้เริ่มอัตโนมัติเมื่อบูต):
    sudo systemctl enable mariadb
    
  1. รันสคริปต์การติดตั้งอย่างปลอดภัย:
    sudo mysql_secure_installation
    

ขั้นตอนนี้จะให้คุณตั้งรหัสผ่าน root และลบการตั้งค่าเริ่มต้นที่ไม่จำเป็นออกไป

การติดตั้ง Python และไลบรารีที่จำเป็น

เพื่อเชื่อมต่อ MariaDB กับ Python คุณต้องติดตั้งไลบรารี mariadb.

  1. ติดตั้งไลบรารี mariadb ด้วย pip :
    pip install mariadb
    
  1. ตรวจสอบการติดตั้ง:
    import mariadb
    print("The MariaDB library was installed successfully.")
    

หากไม่มีข้อผิดพลาดใด ๆ การติดตั้งก็สำเร็จแล้ว

ตอนนี้การตั้งค่าสภาพแวดล้อมสำหรับการใช้ Python กับ MariaDB เสร็จสมบูรณ์แล้ว ต่อไปเราจะอธิบายวิธีเชื่อมต่อกับ MariaDB จาก Python.

3. การเชื่อมต่อกับ MariaDB

วิธีเชื่อมต่อกับ MariaDB ด้วย Python

นำเข้าไลบรารีที่จำเป็น

เพื่อเชื่อมต่อกับ MariaDB ให้นำเข้าไลบรารี Python mariadb.

import mariadb

โค้ดพื้นฐานสำหรับเชื่อมต่อฐานข้อมูล

โค้ดต่อไปนี้แสดงวิธีพื้นฐานในการเชื่อมต่อกับ MariaDB ด้วย Python.

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()

ArgumentDescription
hostMariaDB server address (usually localhost)
userDatabase username
passwordDatabase password
databaseDatabase 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
  1. Log in to MariaDB and check the user’s privileges.
    mysql -u root -p
    
  1. Grant the required privileges to the user.
    GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' IDENTIFIED BY 'password' WITH GRANT OPTION;
    FLUSH PRIVILEGES;
    
  1. 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 host setting is incorrect
Solutions
  1. Check whether the server is running.
    sudo systemctl status mariadb
    
  1. If the server is stopped, start it.
    sudo systemctl start mariadb
    
  1. Check that the host setting 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 .env file
  • 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 nameData typeDescription
idINTUser ID (auto-increment)
nameVARCHAR(100)User name (up to 100 characters)
emailVARCHAR(100) UNIQUEEmail address (must be unique)
created_atDATETIMECreated 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 typeUse caseExample
INTInteger values (IDs, etc.)123
VARCHAR(n)Variable-length strings"Alice"
TEXTLong text (1,000+ characters)"This is a long text."
DATEDate2024-02-21
DATETIMEDate and time2024-02-21 12:34:56
BOOLEANBoolean valuesTRUE 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 the cursor object.
  • You can process records one by one using a for loop.

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)

เมื่อทำงานกับฐานข้อมูล สิ่งสำคัญคือต้องใช้ transactions เพื่อรักษา ความสมบูรณ์ของข้อมูล.
โดยเฉพาะอย่างยิ่ง ความสามารถในการ คืนข้อมูลสู่สถานะเดิม (rollback) เมื่อเกิดข้อผิดพลาดระหว่างการประมวลผล เป็นสิ่งจำเป็นสำหรับการรักษาความสอดคล้อง。

ในส่วนนี้ เราจะอธิบายวิธีจัดการ transactions ใน MariaDB โดยใช้ Python。

What is a transaction?

ทรานแซคชันคือกลไกที่ รวมชุดของการดำเนินการฐานข้อมูลเข้าเป็นหน่วยเดียว จัดการ commit การเปลี่ยนแปลงทั้งหมดหากกระบวนการทุกขั้นตอนสำเร็จ และ rollback การเปลี่ยนแปลงทั้งหมดหากเกิดข้อผิดพลาด

Characteristics of transactions

  • ACID properties
  • Atomicity : การดำเนินการทั้งหมดจะเสร็จสมบูรณ์หรือไม่ถูกนำไปใช้เลย
  • Consistency : ความสมบูรณ์ของข้อมูลจะได้รับการรักษา
  • Isolation : ทรานแซคชันที่ทำงานพร้อมกันจะไม่รบกวนกันและกัน
  • Durability : เมื่อ commit แล้ว การเปลี่ยนแปลงจะถูกบันทึกอย่างถาวร

Basic transaction operations (COMMIT and ROLLBACK)

ทรานแซคชันของ MariaDB สามารถควบคุมได้ด้วยคำสั่งต่อไปนี้:

CommandDescription
START TRANSACTION;Begin a transaction
COMMIT;Commit changes (cannot be undone after commit)
ROLLBACK;Cancel changes (restore the original state)

Using transactions in Python

ด้านล่างนี้คือตัวอย่างพื้นฐานของการจัดการทรานแซคชัน MariaDB โดยใช้ Python。

Managing multiple operations within a single transaction

โค้ดต่อไปนี้ปฏิบัติต่อ การแทรกข้อมูลหลายครั้งเป็นทรานแซคชันเดียว และ commit เฉพาะเมื่อการดำเนินการทั้งหมดสำเร็จ

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

Key points

  • ใช้ conn.start_transaction() เพื่อเริ่มทรานแซคชัน
  • ใช้ conn.commit() เพื่อบันทึกการเปลี่ยนแปลงให้เสร็จสมบูรณ์ (ไม่สามารถยกเลิกได้หลังจาก commit)
  • หากเกิดข้อผิดพลาด ให้ใช้ conn.rollback() เพื่อยกเลิกการเปลี่ยนแปลงและคืนสู่สถานะเดิม

Transaction-based error handling

ข้อผิดพลาดอาจเกิดขึ้นระหว่างการดำเนินการฐานข้อมูล.
ตัวอย่างเช่น ที่อยู่อีเมลซ้ำ (การละเมิดข้อจำกัด UNIQUE) หรือ การหมดเวลาของเซิร์ฟเวอร์ อาจเกิดขึ้น。

Transaction management with error handling

โค้ดต่อไปนี้เพิ่มตรรกะเพื่อ rollback การเปลี่ยนแปลงและคืนสู่สถานะเดิมหากเกิดข้อผิดพลาดระหว่างการประมวลผล

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}")

Summary

ในส่วนนี้ เราอธิบาย พื้นฐานของทรานแซคชันและวิธีการนำไปใช้ใน Python

  • ความสำคัญของทรานแซคชันและคุณสมบัติ ACID
  • วิธีใช้ commit() และ rollback() ใน Python
  • การจัดการทรานแซคชันที่รวมกับการจัดการข้อผิดพลาด

7. การจัดการข้อผิดพลาด (ข้อผิดพลาดทั่วไปและวิธีแก้)

เมื่อทำงานกับ MariaDB ใน Python อาจเกิดข้อผิดพลาดได้.
โดยเฉพาะ ข้อผิดพลาดการเชื่อมต่อฐานข้อมูล, ข้อผิดพลาดไวยากรณ์ SQL, และข้อผิดพลาดความสมบูรณ์ของข้อมูล เป็นข้อผิดพลาดที่พบบ่อย ดังนั้นจึงสำคัญที่ต้องเข้าใจสาเหตุและวิธีแก้ของมัน.

ในส่วนนี้ เราจะแนะนำ สาเหตุของข้อผิดพลาดทั่วไปและวิธีแก้ไข.

Access denied for user (ข้อผิดพลาดการยืนยันตัวตน)

Error message

mariadb.OperationalError: Access denied for user 'root'@'localhost' (using password: YES)

สาเหตุ

  • ชื่อผู้ใช้หรือรหัสผ่านไม่ถูกต้อง
  • ผู้ใช้ MariaDB ไม่มีสิทธิ์ที่เหมาะสม

วิธีแก้

  1. เข้าสู่ระบบ MariaDB และตรวจสอบสิทธิ์ของผู้ใช้
    mysql -u root -p
    
  1. มอบสิทธิ์ให้กับผู้ใช้
    GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' IDENTIFIED BY 'password' WITH GRANT OPTION;
    FLUSH PRIVILEGES;
    
  1. รีสตาร์ท MariaDB
    sudo systemctl restart mariadb
    

Can't connect to MySQL server on 'localhost' (ข้อผิดพลาดการเชื่อมต่อ)

Error message

mariadb.OperationalError: Can't connect to MySQL server on 'localhost' (10061)

สาเหตุ

  • เซิร์ฟเวอร์ MariaDB ไม่ได้ทำงาน
  • การตั้งค่า host ไม่ถูกต้อง

วิธีแก้

  1. ตรวจสอบว่าเซิร์ฟเวอร์ MariaDB ทำงานอยู่หรือไม่
    sudo systemctl status mariadb
    
  1. หากเซิร์ฟเวอร์หยุดทำงาน ให้เริ่มต้นมัน
    sudo systemctl start mariadb
    
  1. ตั้งค่าให้เซิร์ฟเวอร์เริ่มทำงานอัตโนมัติ
    sudo systemctl enable mariadb
    

Unknown database 'sample_db' (ฐานข้อมูลไม่มีอยู่)

Error message

mariadb.ProgrammingError: Unknown database 'sample_db'

สาเหตุ

  • ฐานข้อมูลที่ระบุไม่มีอยู่
  • มีการพิมพ์ผิดในชื่อฐานข้อมูล

วิธีแก้

  1. ตรวจสอบรายการฐานข้อมูล
    SHOW DATABASES;
    
  1. สร้างฐานข้อมูลหากไม่มีอยู่
    CREATE DATABASE sample_db;
    

Table doesn't exist (ตารางไม่มีอยู่)

Error message

mariadb.ProgrammingError: Table 'sample_db.users' doesn't exist

สาเหตุ

  • ตารางที่ระบุไม่มีอยู่
  • ไม่ได้เลือกฐานข้อมูลโดยใช้ USE sample_db;

วิธีแก้

  1. ตรวจสอบรายการตาราง
    SHOW TABLES;
    
  1. สร้างตารางหากไม่มีอยู่
    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 (ข้อผิดพลาดข้อมูลซ้ำ)

Error message

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 (จำนวนพารามิเตอร์ไม่ตรงกัน)

Error message

mariadb.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 2, and there are 1 supplied.

สาเหตุ

  • จำนวนพารามิเตอร์ที่คำสั่ง SQL ต้องการไม่ตรงกับจำนวนอาร์กิวเมนต์ที่ให้มา

วิธีแก้

  • ตรวจสอบให้จำนวน placeholder ตรงกับจำนวนพารามิเตอร์

โค้ดที่ไม่ถูกต้อง

cursor.execute("INSERT INTO users (name, email) VALUES (?, ?)", ("Alice"))

โค้ดที่ถูกต้อง

cursor.execute("INSERT INTO users (name, email) VALUES (?, ?)", ("Alice", "alice@example.com"))

สรุป

ในส่วนนี้ เราได้อธิบายข้อผิดพลาดทั่วไปที่เกิดขึ้นเมื่อทำงานกับ MariaDB ใน Python และวิธีการแก้ไข

  • Access denied for user (ข้อผิดพลาดการตรวจสอบสิทธิ์)
  • Can't connect to MySQL server (ข้อผิดพลาดการเชื่อมต่อ)
  • Unknown database (ฐานข้อมูลไม่มีอยู่)
  • Table doesn't exist (ตารางไม่มีอยู่)
  • Duplicate entry (ข้อผิดพลาดข้อมูลซ้ำ)
  • Incorrect number of bindings (จำนวนพารามิเตอร์ไม่ตรงกัน)

8. สรุป

ในบทความนี้ เราได้อธิบาย วิธีการทำงานกับ MariaDB ด้วย Python ตั้งแต่แนวคิดพื้นฐานจนถึงหัวข้อขั้นสูงกว่า โดยการเข้าใจการดำเนินการฐานข้อมูลพื้นฐานและการนำการจัดการข้อผิดพลาดและการจัดการธุรกรรมไปใช้อย่างถูกต้อง คุณจะสามารถทำการดำเนินการข้อมูลได้อย่างปลอดภัยและมีประสิทธิภาพมากขึ้น

สรุปบทความ

การตั้งค่าสภาพแวดล้อม

  • วิธีการติดตั้ง MariaDB (Windows / Mac / Linux)
  • วิธีการติดตั้งไลบรารีตัวเชื่อมต่อ MariaDB (mariadb) สำหรับ Python

การเชื่อมต่อกับ MariaDB

  • วิธีการเชื่อมต่อฐานข้อมูลพื้นฐาน
  • การเชื่อมต่อที่ปลอดภัยโดยใช้ตัวแปรสภาพแวดล้อม
  • วิธีแก้ไขข้อผิดพลาดการเชื่อมต่อทั่วไป

การสร้างฐานข้อมูลและตาราง

  • การสร้างฐานข้อมูล (SQL / Python)
  • การสร้างตารางและการเลือกประเภทข้อมูล
  • การตรวจสอบและลบตารางที่มีอยู่

การดำเนินการ CRUD (Create, Read, Update, Delete)

  • การดำเนินการข้อมูลพื้นฐานด้วย Python
  • การใช้ตัวแทนเพื่อป้องกันการฉีด SQL
  • การจัดการข้อผิดพลาดอย่างเหมาะสม

การทำธุรกรรมและการย้อนกลับ

  • ความสำคัญของธุรกรรม (คุณสมบัติ ACID)
  • วิธีการกู้คืนข้อมูลเมื่อเกิดข้อผิดพลาด (rollback)
  • การจัดการธุรกรรมด้วยตนเองโดยปิด AutoCommit

การจัดการข้อผิดพลาด (ข้อผิดพลาดทั่วไปและวิธีแก้)

  • ข้อผิดพลาดการตรวจสอบสิทธิ์ (Access denied for user)
  • ข้อผิดพลาดการเชื่อมต่อ (Can't connect to MySQL server)
  • ข้อผิดพลาดฐานข้อมูลหรือ ตารางไม่พบ
  • ข้อผิดพลาดข้อมูลซ้ำ (Duplicate entry)
  • การจัดการ deadlock และการใช้ตรรกะลองใหม่

จุดสำคัญเมื่อรวม Python กับ MariaDB

  1. ใช้ตัวแทน
    cursor.execute("INSERT INTO users (name, email) VALUES (?, ?)", ("Alice", "alice@example.com"))
    

→ ใช้ตัวแปรผูกแทนการฝังโดยตรงในคำสั่ง SQL เพื่อ ป้องกันการฉีด SQL.

  1. จัดการธุรกรรมอย่างเหมาะสม
  • ใช้ conn.commit() เพื่อ ทำการคอมมิตการเปลี่ยนแปลงอย่างชัดเจน .
  • ใช้ conn.rollback() เมื่อเกิดข้อผิดพลาดเพื่อ รักษาความสมบูรณ์ของข้อมูล .
  1. ดำเนินการจัดการข้อผิดพลาดอย่างละเอียด
  • ใช้บล็อก try-except เพื่อ ดักจับข้อผิดพลาดที่อาจเกิดขึ้นล่วงหน้า .
  • เตรียมกลยุทธ์การจัดการเฉพาะสำหรับข้อผิดพลาดเช่น OperationalError และ IntegrityError .
  1. พิจารณาประสิทธิภาพ
  • การแทรกแบบกลุ่ม (แทรกหลายเรคคอร์ดพร้อมกัน)
  • การทำดัชนีที่เหมาะสม (ปรับปรุงประสิทธิภาพการค้นหา)

แหล่งข้อมูลสำหรับการเรียนรู้ต่อเนื่อง

หากคุณต้องการเพิ่มพูนความเข้าใจในการผสานรวม Python กับ MariaDB ให้พิจารณาแหล่งข้อมูลต่อไปนี้:

เอกสารอย่างเป็นทางการ

เนื้อหาการเรียนรู้ที่เกี่ยวข้อง

หนังสือแนะนำ

สรุป

โดยการผสาน MariaDB กับ Python คุณสามารถเปิดใช้งาน การจัดการข้อมูลแบบสคริปต์ และ การอัตโนมัติ. ด้วยการนำไปใช้ไม่เพียงแต่การดำเนินการ CRUD พื้นฐานเท่านั้น แต่ยังรวมถึง การจัดการข้อผิดพลาดและการจัดการธุรกรรม อย่างเหมาะสม คุณจะสามารถสร้างระบบที่ปลอดภัยและมีประสิทธิภาพมากขึ้น.

ในขั้นตอนต่อไป พิจารณาเรียนรู้เกี่ยวกับ การจัดการข้อมูลที่มีประสิทธิภาพ และ การบูรณาการ API เพื่อประยุกต์ความรู้ของคุณกับการดำเนินการฐานข้อมูลเชิงปฏิบัติ