Hướng dẫn Python MariaDB: Kết nối, CRUD, Giao dịch và Xử lý lỗi

目次

1. Giới thiệu

Dành cho những ai muốn làm việc với MariaDB trong Python

Nhiều người muốn kết nối tới MariaDB bằng Python và thao tác dữ liệu. Trong bài viết này, chúng tôi sẽ giải thích mọi thứ từ cơ bản đến các chủ đề nâng cao hơn để làm việc với MariaDB bằng Python.

Bạn có gặp một trong những vấn đề sau không?

  • Bạn không biết cách kết nối tới MariaDB từ Python
  • Bạn muốn dễ dàng tạo, đọc, cập nhật và xóa dữ liệu trong MariaDB bằng Python
  • Bạn muốn tìm hiểu các lỗi thường gặp và cách khắc phục chúng

Những gì bạn sẽ học trong bài viết này

  • Cách dễ dàng kết nối tới MariaDB từ Python
  • Cách thực hiện CRUD (Create, Read, Update, Delete)
  • Các lỗi thường gặp và giải pháp của chúng
  • Cách bảo vệ tính toàn vẹn dữ liệu bằng giao dịch (transactions)

Sau khi đọc xong bài viết, bạn sẽ có thể làm việc trơn tru với MariaDB bằng Python. Bây giờ, hãy cùng đi sâu vào chi tiết.

2. Cài đặt môi trường (Cài đặt MariaDB & Python)

MariaDB là gì?

MariaDB là một hệ quản trị cơ sở dữ liệu quan hệ (RDBMS) mã nguồn mở, được sử dụng rộng rãi như là người kế thừa của MySQL. Trong khi duy trì tính tương thích cao với MySQL, MariaDB đã cải thiện hiệu năng và bổ sung các tính năng mới.

Công cụ cần thiết

Để làm việc với MariaDB trong Python, bạn cần chuẩn bị các công cụ sau:

  • Python (phiên bản 3.x hoặc mới hơn được khuyến nghị)
  • MariaDB (máy chủ)
  • Trình kết nối MariaDB cho Python (thư viện mariadb)

Cách cài đặt MariaDB (theo hệ điều hành)

Đối với Windows

  1. Tải trình cài đặt MariaDB từ trang web chính thức .
  2. Chạy trình cài đặt và làm theo các hướng dẫn để hoàn tất việc cài đặt.
  3. Sau khi cài đặt, xác minh MariaDB đang hoạt động bằng cách chạy lệnh sau:
    mysql -u root -p
    
  1. Nếu bạn có thể đăng nhập thành công, việc cài đặt đã hoàn tất.

Đối với Mac

Trên macOS, bạn có thể dễ dàng cài đặt MariaDB bằng Homebrew.

  1. Nếu Homebrew chưa được cài đặt, hãy cài đặt nó bằng lệnh sau:
    /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
    
  1. Cài đặt MariaDB:
    brew install mariadb
    
  1. Khởi động MariaDB:
    brew services start mariadb
    
  1. Xác minh việc cài đặt:
    mysql -u root -p
    

Đối với Linux (Ubuntu)

  1. Cập nhật danh sách gói và cài đặt MariaDB:
    sudo apt update
    sudo apt install mariadb-server mariadb-client
    
  1. Khởi động MariaDB:
    sudo systemctl start mariadb
    
  1. Kích hoạt MariaDB (tự động khởi động khi khởi động hệ thống):
    sudo systemctl enable mariadb
    
  1. Chạy script cài đặt bảo mật:
    sudo mysql_secure_installation
    

Điều này cho phép bạn đặt mật khẩu root và loại bỏ các cài đặt mặc định không cần thiết.

Cài đặt Python và thư viện cần thiết

Để tích hợp MariaDB với Python, bạn cần cài đặt thư viện mariadb.

  1. Cài đặt thư viện mariadb bằng pip :
    pip install mariadb
    
  1. Xác minh việc cài đặt:
    import mariadb
    print("The MariaDB library was installed successfully.")
    

Nếu không có lỗi nào xuất hiện, việc cài đặt đã thành công.

Bây giờ môi trường của bạn để sử dụng Python với MariaDB đã sẵn sàng. Tiếp theo, chúng tôi sẽ giải thích cách kết nối tới MariaDB từ Python.

3. Kết nối tới MariaDB

Cách kết nối tới MariaDB bằng Python

Nhập thư viện cần thiết

Để kết nối tới MariaDB, nhập thư viện Python mariadb.

import mariadb

Mã cơ bản để kết nối tới cơ sở dữ liệu

Đoạn mã dưới đây cho thấy cách cơ bản để kết nối tới MariaDB bằng 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!")

    # Tạo một con trỏ
    cursor = conn.cursor()

    # Nếu kết nối thành công, đóng nó
    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

# Tải tệp .env
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

# Kết nối cơ sở dữ liệu (không chỉ định cơ sở dữ liệu)
config = {
    "host": "localhost",
    "user": "root",
    "password": "password"
}

try:
    conn = mariadb.connect(**config)
    cursor = conn.cursor()

    # Tạo cơ sở dữ liệu
    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"Đã xảy ra lỗi: {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

# Kết nối cơ sở dữ liệu
config = {
    "host": "localhost",
    "user": "root",
    "password": "password",
    "database": "sample_db"
}

try:
    conn = mariadb.connect(**config)
    cursor = conn.cursor()

    # SQL tạo bảng
    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("Đã tạo bảng 'users'.")

    cursor.close()
    conn.close()
except mariadb.Error as e:
    print(f"Đã xảy ra lỗi: {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

# Cài đặt kết nối cơ sở dữ liệu
config = {
    "host": "localhost",
    "user": "root",
    "password": "password",
    "database": "sample_db"
}

try:
    conn = mariadb.connect(**config)
    cursor = conn.cursor()

    # Chèn dữ liệu
    insert_query = "INSERT INTO users (name, email) VALUES (?, ?)"
    data = ("Alice", "alice@example.com")
    cursor.execute(insert_query, data)

    # Lưu thay đổi
    conn.commit()
    print("Dữ liệu đã được chèn thành công!")

    cursor.close()
    conn.close()
except mariadb.Error as e:
    print(f"Đã xảy ra lỗi: {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()

    # Lấy dữ liệu
    select_query = "SELECT id, name, email FROM users"
    cursor.execute(select_query)

    # Hiển thị dữ liệu đã lấy
    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"Đã xảy ra lỗi: {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()

    # Cập nhật dữ liệu
    update_query = "UPDATE users SET name = ? WHERE email = ?"
    data = ("Alice Smith", "alice@example.com")
    cursor.execute(update_query, data)

    # Lưu thay đổi
    conn.commit()
    print("Dữ liệu đã được cập nhật thành công!")

    cursor.close()
    conn.close()
except mariadb.Error as e:
    print(f"Đã xảy ra lỗi: {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()

    # Xóa dữ liệu
    delete_query = "DELETE FROM users WHERE email = ?"
    data = ("alice@example.com",)
    cursor.execute(delete_query, data)

    # Lưu thay đổi
    conn.commit()
    print("Dữ liệu đã được xóa thành công!")

    cursor.close()
    conn.close()
except mariadb.Error as e:
    print(f"Đã xảy ra lỗi: {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)

Khi làm việc với cơ sở dữ liệu, việc sử dụng giao dịch để duy trì tính toàn vẹn dữ liệu là rất quan trọng.
Đặc biệt, khả năng khôi phục dữ liệu về trạng thái ban đầu (rollback) khi xảy ra lỗi trong quá trình xử lý là thiết yếu để duy trì tính nhất quán.

Trong phần này, chúng tôi sẽ giải thích cách quản lý giao dịch trong MariaDB bằng Python.

Giao dịch là gì?

Giao dịch là một cơ chế nhóm một loạt các thao tác cơ sở dữ liệu thành một đơn vị duy nhất, cam kết tất cả các thay đổi nếu mọi quá trình thành công, và hoàn tác (rollback) tất cả các thay đổi nếu có lỗi xảy ra.

Đặc điểm của giao dịch

  • Các thuộc tính ACID
  • Atomicity : Tất cả các thao tác hoặc hoàn thành thành công, hoặc không có thao tác nào được áp dụng.
  • Consistency : Tính toàn vẹn dữ liệu được duy trì.
  • Isolation : Các giao dịch đồng thời không can thiệp lẫn nhau.
  • Durability : Khi đã cam kết, các thay đổi được lưu vĩnh viễn.

Các thao tác giao dịch cơ bản (COMMIT và ROLLBACK)

Các giao dịch MariaDB có thể được điều khiển bằng các lệnh sau:

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

Sử dụng giao dịch trong Python

Dưới đây là một ví dụ cơ bản về quản lý giao dịch MariaDB bằng Python.

Quản lý nhiều thao tác trong một giao dịch duy nhất

Đoạn mã sau xử lý nhiều thao tác chèn như một giao dịch và chỉ cam kết nếu tất cả các thao tác đều thành công.

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

Các điểm chính

  • Dùng conn.start_transaction() để bắt đầu một giao dịch.
  • Dùng conn.commit() để hoàn tất các thay đổi (không thể hoàn tác sau khi cam kết).
  • Nếu xảy ra lỗi, dùng conn.rollback() để hủy các thay đổi và khôi phục trạng thái ban đầu.

Xử lý lỗi dựa trên giao dịch

Lỗi có thể xảy ra trong quá trình thao tác cơ sở dữ liệu.
Ví dụ, địa chỉ email trùng lặp (vi phạm ràng buộc UNIQUE) hoặc hết thời gian chờ của máy chủ có thể xảy ra.

Quản lý giao dịch với xử lý lỗi

Đoạn mã sau thêm logic để hoàn tác các thay đổi và khôi phục trạng thái ban đầu nếu có lỗi xảy ra trong quá trình xử lý.

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

Tóm tắt

Trong phần này, chúng tôi đã giải thích các kiến thức cơ bản về giao dịch và cách triển khai chúng trong Python.

  • Tầm quan trọng của giao dịch và các thuộc tính ACID
  • Cách sử dụng commit()rollback() trong Python
  • Quản lý giao dịch kết hợp với xử lý lỗi

7. Xử lý lỗi (Các lỗi thường gặp và giải pháp)

Khi làm việc với MariaDB trong Python, lỗi có thể xảy ra.
Đặc biệt, lỗi kết nối cơ sở dữ liệu, lỗi cú pháp SQL và lỗi toàn vẹn dữ liệu là những lỗi phổ biến, vì vậy việc hiểu nguyên nhân và cách khắc phục chúng là rất quan trọng.

Trong phần này, chúng tôi giới thiệu nguyên nhân của các lỗi thường gặp và cách sửa chúng.

Access denied for user (Lỗi xác thực)

Thông báo lỗi

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

Nguyên nhân

  • Tên người dùng hoặc mật khẩu không đúng
  • Người dùng MariaDB không có quyền thích hợp

Giải pháp

  1. Đăng nhập vào MariaDB và kiểm tra quyền của người dùng
    mysql -u root -p
    
  1. Cấp quyền cho người dùng
    GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' IDENTIFIED BY 'password' WITH GRANT OPTION;
    FLUSH PRIVILEGES;
    
  1. Khởi động lại MariaDB
    sudo systemctl restart mariadb
    

Can't connect to MySQL server on 'localhost' (Lỗi kết nối)

Thông báo lỗi

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

Nguyên nhân

  • Máy chủ MariaDB không đang chạy
  • Cài đặt host không đúng

Giải pháp

  1. Kiểm tra xem máy chủ MariaDB có đang chạy không
    sudo systemctl status mariadb
    
  1. Nếu máy chủ đã dừng, khởi động lại nó
    sudo systemctl start mariadb
    
  1. Cho phép máy chủ tự động khởi động
    sudo systemctl enable mariadb
    

Unknown database 'sample_db' (Cơ sở dữ liệu không tồn tại)

Thông báo lỗi

mariadb.ProgrammingError: Unknown database 'sample_db'

Nguyên nhân

  • Cơ sở dữ liệu được chỉ định không tồn tại
  • Có lỗi chính tả trong tên cơ sở dữ liệu

Giải pháp

  1. Kiểm tra danh sách các cơ sở dữ liệu
    SHOW DATABASES;
    
  1. Tạo cơ sở dữ liệu nếu nó chưa tồn tại
    CREATE DATABASE sample_db;
    

Table doesn't exist (Bảng không tồn tại)

Thông báo lỗi

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

Nguyên nhân

  • Bảng được chỉ định không tồn tại
  • Cơ sở dữ liệu chưa được chọn bằng câu lệnh USE sample_db;

Giải pháp

  1. Kiểm tra danh sách các bảng
    SHOW TABLES;
    
  1. Tạo bảng nếu nó chưa tồn tại
    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 (Lỗi dữ liệu trùng lặp)

Thông báo lỗi

mariadb.IntegrityError: Duplicate entry 'alice@example.com' for key 'users.email'

Nguyên nhân

  • Cột email có ràng buộc UNIQUE, vì vậy không thể chèn các giá trị trùng lặp

Giải pháp

  • Kiểm tra trùng lặp trước khi chèn dữ liệu
  • Sử dụng ON DUPLICATE KEY UPDATE

Mã Python để ngăn chặn trùng lặp

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

Hoặc sử dụng 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 (Số lượng tham số không khớp)

Thông báo lỗi

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

Nguyên nhân

  • Số lượng tham số yêu cầu bởi câu lệnh SQL không khớp với số lượng đối số được cung cấp

Giải pháp

  • Đảm bảo số lượng placeholder khớp với số lượng tham số

Mã không đúng

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

Mã đúng

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

Tóm tắt

Trong phần này, chúng tôi đã giải thích các lỗi phổ biến xảy ra khi làm việc với MariaDB trong Python và cách khắc phục chúng.

  • Access denied for user (Lỗi xác thực)
  • Can't connect to MySQL server (Lỗi kết nối)
  • Unknown database (Cơ sở dữ liệu không tồn tại)
  • Table doesn't exist (Bảng không tồn tại)
  • Duplicate entry (Lỗi dữ liệu trùng lặp)
  • Incorrect number of bindings (Số lượng tham số không khớp)

8. Kết luận

Trong bài viết này, chúng tôi đã giải thích cách làm việc với MariaDB bằng Python, từ các khái niệm cơ bản đến các chủ đề nâng cao.
Bằng cách hiểu các thao tác cơ bản của cơ sở dữ liệu và triển khai đúng cách xử lý lỗi và quản lý giao dịch, bạn có thể thực hiện các thao tác dữ liệu an toàn và hiệu quả hơn.

Tóm tắt bài viết

Cài đặt môi trường

  • Cách cài đặt MariaDB (Windows / Mac / Linux)
  • Cách cài đặt thư viện kết nối MariaDB (mariadb) cho Python

Kết nối tới MariaDB

  • Các phương pháp kết nối cơ sở dữ liệu cơ bản
  • Kết nối bảo mật bằng biến môi trường
  • Giải pháp cho các lỗi kết nối thường gặp

Tạo cơ sở dữ liệu và bảng

  • Tạo cơ sở dữ liệu (SQL / Python)
  • Tạo bảng và chọn kiểu dữ liệu
  • Kiểm tra và xóa các bảng hiện có

Các thao tác CRUD (Create, Read, Update, Delete)

  • Các thao tác dữ liệu cơ bản bằng Python
  • Sử dụng placeholder để ngăn chặn SQL injection
  • Xử lý lỗi đúng cách

Giao dịch và rollback

  • Tầm quan trọng của giao dịch (đặc tính ACID)
  • Cách khôi phục dữ liệu khi lỗi (rollback)
  • Quản lý giao dịch thủ công bằng cách tắt AutoCommit

Xử lý lỗi (Các lỗi thường gặp và giải pháp)

  • Lỗi xác thực (Access denied for user)
  • Lỗi kết nối (Can't connect to MySQL server)
  • Lỗi không tìm thấy cơ sở dữ liệu hoặc bảng
  • Lỗi dữ liệu trùng lặp (Duplicate entry)
  • Xử lý deadlock và triển khai logic thử lại

Các điểm quan trọng khi kết hợp Python và MariaDB

  1. Sử dụng placeholder
    cursor.execute("INSERT INTO users (name, email) VALUES (?, ?)", ("Alice", "alice@example.com"))
    

→ Gắn biến thay vì nhúng trực tiếp vào câu lệnh SQL để ngăn chặn SQL injection.

  1. Quản lý giao dịch đúng cách
  • Sử dụng conn.commit() để cam kết các thay đổi một cách rõ ràng .
  • Sử dụng conn.rollback() khi có lỗi để giữ nguyên tính toàn vẹn dữ liệu .
  1. Triển khai xử lý lỗi toàn diện
  • Sử dụng khối try-except để bắt các lỗi tiềm ẩn trước .
  • Chuẩn bị các chiến lược xử lý cụ thể cho các lỗi như OperationalErrorIntegrityError .
  1. Xem xét hiệu năng
  • Chèn hàng loạt (chèn nhiều bản ghi cùng lúc)
  • Tạo chỉ mục hợp lý (cải thiện hiệu suất tìm kiếm)

Tài nguyên để học thêm

Nếu bạn muốn hiểu sâu hơn về việc tích hợp Python và MariaDB, hãy xem các tài nguyên sau:

Tài liệu chính thức

Nội dung học liên quan

Sách đề xuất

Tóm tắt

Bằng cách tích hợp MariaDB với Python, bạn có thể thực hiện quản lý dữ liệu dựa trên scripttự động hoá.
Bằng cách triển khai không chỉ các thao tác CRUD cơ bản mà còn xử lý lỗi và quản lý giao dịch đúng cách, bạn có thể xây dựng một hệ thống an toàn và hiệu quả hơn.

Bước tiếp theo, hãy cân nhắc học về quản lý dữ liệu hiệu quảtích hợp API để áp dụng kiến thức của bạn vào các hoạt động cơ sở dữ liệu thực tiễn.