Python MariaDB උපදෙස්: සම්බන්ධ කිරීම, CRUD, ගනුදෙනු, සහ දෝෂ නිරාකරණය

目次

1. හැඳින්වීම

Python හි MariaDB සමඟ වැඩ කිරීමට කැමති අය සඳහා

බොහෝ දෙනා Python භාවිතයෙන් MariaDB වෙත සම්බන්ධ වී දත්ත සැකසීමට අවශ්‍ය වේ. මෙම ලිපියේ, Python සමඟ MariaDB භාවිතය සඳහා මූලික කරුණු සිට උසස් මාතෘකා දක්වා සියල්ල පැහැදිලි කරමු.

ඔබට මෙම ගැටළු වලින් කිසිවක් තිබේද?

  • Python වෙතින් MariaDB වෙත සම්බන්ධ වීමට ඔබ නොදනී
  • Python භාවිතයෙන් MariaDB හි දත්ත සාදන්න, කියවන්න, යාවත්කාලීන කරන්න, මකා දැමීමට ඔබට පහසුවෙන් අවශ්‍යයි
  • පොදු දෝෂ සහ ඒවා සකස් කිරීම පිළිබඳ ඔබට ඉගෙන ගැනීමට අවශ්‍යයි

ඔබ මෙම ලිපියෙන් ඉගෙන ගන්නා දේ

  • Python වෙතින් MariaDB වෙත පහසුවෙන් සම්බන්ධ වීම
  • CRUD (Create, Read, Update, Delete) ක්‍රියාත්මක කිරීම
  • පොදු දෝෂ සහ ඒවාගේ විසඳුම්
  • ගනුදෙනු (transactions) සමඟ දත්ත අඛණ්ඩතාව රැක ගැනීම

මෙම ලිපිය කියවා අවසන් වූ පසු, Python භාවිතයෙන් MariaDB සමඟ සාර්ථකව වැඩ කිරීමට ඔබට හැකි වනු ඇත. දැන්, විස්තර වෙත ගොඩවෙමු.

2. පරිසර සැකසුම (MariaDB සහ Python ස්ථාපනය කිරීම)

MariaDB යනු කුමක්ද?

MariaDB යනු විවෘත-මූලාශ්‍ර සම්බන්ධක දත්ත ගබඩා කළමනාකරණ පද්ධතිය (RDBMS) වන අතර MySQL හි පසුගාමී ලෙස පුළුල්ව භාවිත වේ. MySQL සමඟ ඉහළ අනුකූලතාවය රැකගෙන, MariaDB වැඩි කාර්ය සාධනය සහ නව විශේෂාංග එක් කර ඇත.

අවශ්‍ය මෙවලම්

Python හි MariaDB සමඟ වැඩ කිරීමට, පහත සඳහන් මෙවලම් සූදානම් කරගත යුතුය:

  • Python (3.x හෝ ඊට පසු සංස්කරණය නිර්දේශිත)
  • MariaDB (සේවාදායකය)
  • MariaDB Python සම්බන්ධක (mariadb පුස්තකාලය)

MariaDB ස්ථාපනය කිරීම (ඔපරේටින් පද්ධතිය අනුව)

Windows සඳහා

  1. අධිකාරී වෙබ් අඩවිය වෙතින් MariaDB ස්ථාපකය බාගන්න.
  2. ස්ථාපකය ධාවනය කර, උපදෙස් අනුගමනය කර ස්ථාපනය සම්පූර්ණ කරන්න.
  3. ස්ථාපනයෙන් පසු, පහත කමාන්ඩ් එක ධාවනය කර MariaDB ක්‍රියාත්මක වන බව තහවුරු කරන්න:
    mysql -u root -p
    
  1. ඔබට සාර්ථකව ලොග් විය හැකි නම්, ස්ථාපනය සම්පූර්ණයි.

Mac සඳහා

Mac හි, Homebrew භාවිතයෙන් MariaDB පහසුවෙන් ස්ථාපනය කළ හැක.

  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 සහ අවශ්‍ය පුස්තකාලය ස්ථාපනය කිරීම

Python සමඟ MariaDB එකතු කිරීමට, mariadb පුස්තකාලය ස්ථාපනය කළ යුතුය.

  1. pip භාවිතයෙන් mariadb පුස්තකාලය ස්ථාපනය කරන්න:
    pip install mariadb
    
  1. ස්ථාපනය තහවුරු කරන්න:
    import mariadb
    print("The MariaDB library was installed successfully.")
    

දෝෂයක් නොමැතිව සම්පූර්ණ වූ නම්, ස්ථාපනය සාර්ථකයි.

දැන් Python සමඟ MariaDB භාවිතයට ඔබේ පරිසර සැකසුම සම්පූර්ණයි. ඊළඟට, Python වෙතින් MariaDB වෙත සම්බන්ධ වීමේ ක්‍රමය පැහැදිලි කරමු.

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

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)

ඩේටාබේස් එකක් සමඟ වැඩ කරන විට, data integrity රැක ගැනීම සඳහා transactions භාවිතා කිරීම වැදගත් ය.
විශේෂයෙන්ම, ප්‍රතිකාරණයේදී දෝෂයක් සිදු වන විට data එහි මුල් තත්ත්වයට ප්‍රතිස්ථාපනය කිරීමේ හැකියාව (rollback) consistency රැක ගැනීම සඳහා අත්‍යවශ්‍ය ය.

මෙම කොටසේදී, අපි Python භාවිතයෙන් MariaDB හි transactions manage කරන්නේ කෙසේදැයි පැහැදිලි කරන්නෙමු.

Transaction යනු කුමක්ද?

Transaction යනු ඩේටාබේස් මෙහෙයුම් රැසක එක ඒකකයක් බවට පරිගණනය කිරීමේ මෙකොන්සම් එකක් වන අතර, සෑම ක්‍රියාවලියක්ම සාර්ථක වුවහොත් සියලු වෙනස්කම් commit කරයි, සහ දෝෂයක් සිදු වුවහොත් සියලු වෙනස්කම් rollback කරයි.

Transactions හි ලක්ෂණ

  • ACID properties
  • Atomicity : සියලු මෙහෙයුම් සාර්ථකව අවසන් වන්නේ නැතිනම් කිසිවක් apply නොවේ.
  • Consistency : Data integrity රැක ගනී.
  • Isolation : සමකාලීන transactions එකිනෙකට බාධා කරන්නේ නැත.
  • Durability : Commit වූ පසු, වෙනස්කම් ස්ථිරව සුරැකී ඇත.

මූලික transaction මෙහෙයුම් (COMMIT සහ ROLLBACK)

MariaDB transactions පහත commands භාවිතයෙන් පාලනය කළ හැක:

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

Python හි transactions භාවිතා කිරීම

පහත දැක්වෙන්නේ Python භාවිතයෙන් MariaDB transactions manage කිරීමේ මූලික උදාහරණයකි.

එක transaction එකක් තුළ බහු මෙහෙයුම් manage කිරීම

පහත කේතය බහු insert මෙහෙයුම් එක 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

  • Transaction එකක් ආරම්භ කිරීම සඳහා conn.start_transaction() භාවිතා කරන්න.
  • වෙනස්කම් අවසන් කිරීම සඳහා conn.commit() භාවිතා කරන්න (commit කළ පසු undo කළ නොහැක).
  • දෝෂයක් සිදු වුවහොත්, වෙනස්කම් අවලංගු කිරීමට සහ මුල් තත්ත්වයට ප්‍රතිස්ථාපනය කිරීමට conn.rollback() භාවිතා කරන්න.

Transaction මූලික error handling

ඩේටාබේස් මෙහෙයුම්වලදී දෝෂ සිදු විය හැක.
උදාහරණයක් ලෙස, duplicate email address (UNIQUE constraint violation) හෝ server timeout සිදු විය හැක.

Error handling සමඟ transaction management

පහත කේතය ප්‍රතිකාරණයේදී දෝෂයක් සිදු වුවහොත් වෙනස්කම් rollback කරන අතර මුල් තත්ත්වයට ප්‍රතිස්ථාපනය කිරීමේ logic එකතු කරයි.

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

සාරාංශය

මෙම කොටසේදී, අපි transactions හි මූලික සහ Python හි ඒවා implement කිරීමේ ක්‍රම පැහැදිලි කළෙමු.

  • Transactions සහ ACID properties හි වැදගත්කම
  • Python හි commit() සහ rollback() භාවිතා කිරීමේ ක්‍රම
  • Error handling සමඟ ඒකාබද්ධ transaction management

7. දෝෂ හසුරවීම (සාමාන්‍ය දෝෂ සහ විසඳුම්)

Python හි MariaDB සමඟ වැඩ කරන විට දෝෂ ඇති විය හැක.
විශේෂයෙන්, දත්ත ගබඩා සම්බන්ධතා දෝෂ, SQL වාක්‍ය රචනා දෝෂ, සහ දත්ත අඛණ්ඩතාව දෝෂ සාමාන්‍ය වේ, එබැවින් ඒවායේ හේතු සහ විසඳුම් තේරුම් ගැනීම වැදගත්ය.

මෙම කොටසේ, සාමාන්‍ය දෝෂ들의 හේතු සහ ඒවා සකස් කරන ආකාරය හඳුන්වා දෙමු.

Access denied for user (සත්‍යාපන දෝෂ)

දෝෂ පණිවුඩය

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' (සම්බන්ධතා දෝෂ)

දෝෂ පණිවුඩය

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' (දත්ත ගබඩාව නොමැත)

දෝෂ පණිවුඩය

mariadb.ProgrammingError: Unknown database 'sample_db'

හේතුව

  • සඳහන් කර ඇති දත්ත ගබඩාව නොමැත
  • දත්ත ගබඩාවේ නාමයෙහි අක්ෂර දෝෂයක් ඇත

විසඳුම

  1. දත්ත ගබඩා ලැයිස්තුව පරීක්ෂා කරන්න
    SHOW DATABASES;
    
  1. දත්ත ගබඩාව නොමැති නම්, එය සාදන්න
    CREATE DATABASE sample_db;
    

Table doesn't exist (වගුව නොමැත)

දෝෂ පණිවුඩය

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 (අනුපිළිවෙළ දත්ත දෝෂ)

දෝෂ පණිවුඩය

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 ප්‍රකාශයට අවශ්‍ය පරාමිතීන් ගණන, ලබා දී ඇති arguments ගණනට නොගැලපේ

විසඳුම

  • පිළිවෙළකරු (placeholder) ගණන පරාමිතීන් ගණනට සමාන බවට සහතික වන්න

වැරදි කේතය

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 ඉන්ජෙක්ශන් වැළැක්වීමට placeholders භාවිතය
  • නිවැරදි දෝෂ හසුරුවීම

ගනුදෙනු සහ rollback

  • ගනුදෙනු (ACID ගුණාංග) වැදගත්කම
  • දෝෂයක් සිදුවේවිට දත්ත ප්‍රතිස්ථාපනය (rollback) කිරීම
  • AutoCommit අක්‍රිය කිරීමෙන් ගනුදෙනු අතින් කළමනාකරණය

දෝෂ හසුරුවීම (සාමාන්‍ය දෝෂ සහ විසඳුම්)

  • සත්‍යාපන දෝෂ (Access denied for user)
  • සම්බන්ධතා දෝෂ (Can't connect to MySQL server)
  • දත්ත ගබඩා හෝ වගුව නොමැති දෝෂ
  • අනුපිටපත් දත්ත දෝෂ (Duplicate entry)
  • ඩෙඩ්ලොක්ස් හසුරුවීම සහ නැවත උත්සාහ කිරීමේ තර්කය

Python සහ MariaDB එකතු කිරීමේ මූලික කරුණු

  1. Placeholders භාවිතා කරන්න
    cursor.execute("INSERT INTO users (name, email) VALUES (?, ?)", ("Alice", "alice@example.com"))
    

→ SQL ප්‍රකාශන තුළ සෘජුව ඇතුළත් කිරීම වෙනුවට බයින්ඩ් වාරියබල් භාවිතා කර SQL ඉන්ජෙක්ශන් වැළැක්වන්න.

  1. ගනුදෙනු නිවැරදිව කළමනාකරණය කරන්න
    conn.commit() භාවිතා කර වෙනස්කම් පැහැදිලිව commit කරන්න.
    දෝෂයක් සිදුවේවිට conn.rollback() භාවිතා කර දත්ත අඛණ්ඩතාව රැකගන්න.

  2. විස්තරාත්මක දෝෂ හසුරුවීම ක්‍රියාත්මක කරන්න
    try-except බ්ලොක් භාවිතා කර දෝෂයන් පෙරදැරිව අල්ලා ගන්න.
    OperationalError සහ IntegrityError වැනි දෝෂ සඳහා විශේෂිත හසුරුවීම්ยุත්‍රණ සැකසිය යුතුය.

  3. කාර්යක්ෂමතාවය සැලකිල්ලට ගන්න
    Bulk inserts (එකවර බහු රෙකෝඩ් ඇතුළත් කිරීම)
    නිවැරදි ඉන්ඩෙක්සිං (සෙවීමේ කාර්යක්ෂමතාව වැඩි කිරීම)

අතිරේක ඉගෙනුම් සම්පත්

Python සහ MariaDB එකතු කිරීමේ ඔබේ අවබෝධය ගැඹුරු කිරීමට, පහත සම්පත් සලකා බලන්න:

අධිකාරී ලේඛන

සම්බන්ධිත ඉගෙනුම් අන්තර්ගතය

නිර්දේශිත පොත්

සාරාංශය

Python සමඟ MariaDB එකතු කිරීමෙන්, ස්ක්‍රිප්ට්-අධාරිත දත්ත කළමනාකරණය සහ ස්වයංක්‍රීය කිරීම සක්‍රිය කර ගත හැකිය.
මූලික CRUD මෙහෙයුම් පමණක් නොව, නිවැරදි දෝෂ හසුරුවීම සහ ගනුදෙනු කළමනාකරණයද ක්‍රියාත්මක කිරීමෙන්, ඔබට ආරක්ෂිත හා කාර්යක්ෂම පද්ධතියක් ගොඩනැගිය හැකිය.

ඊළඟ පියවර ලෙස, ඔබේ දැනුම ප්‍රායෝගික දත්ත ගබඩා මෙහෙයුම් වලට යොදා ගැනීමට කාර්යක්ෂම දත්ත කළමනාකරණය සහ API ඒකාබද්ධ කිරීම ගැන ඉගෙන ගැනීමට සලකා බලන්න.