- 1 1. Introduzione
- 2 2. Configurazione dell’Ambiente (Installazione di MariaDB & Python)
- 3 3. Connessione a 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 Riepilogo
- 11 7. Gestione degli errori (Errori comuni e soluzioni)
- 11.1 Access denied for user (Authentication error)
- 11.2 Can't connect to MySQL server on 'localhost' (Connection error)
- 11.3 Unknown database 'sample_db' (Database does not exist)
- 11.4 Table doesn't exist (Table does not exist)
- 11.5 Duplicate entry (Duplicate data error)
- 11.6 Incorrect number of bindings (Parameter count mismatch)
- 12 Sommario
- 13 8. Conclusione
- 14 Sommario
1. Introduzione
Per chi vuole lavorare con MariaDB in Python
Molte persone desiderano connettersi a MariaDB usando Python e manipolare i dati. In questo articolo spiegheremo tutto, dalle basi ai temi più avanzati, per lavorare con MariaDB usando Python.
Hai riscontrato uno di questi problemi?
- Non sai come connetterti a MariaDB da Python
- Vuoi creare, leggere, aggiornare e cancellare dati in MariaDB usando Python in modo semplice
- Vuoi conoscere gli errori più comuni e come risolverli
Cosa imparerai in questo articolo
- Come connettersi facilmente a MariaDB da Python
- Come implementare le operazioni CRUD (Create, Read, Update, Delete)
- Errori comuni e le loro soluzioni
- Come proteggere l’integrità dei dati con le transazioni
Dopo aver letto questo articolo sarai in grado di lavorare senza problemi con MariaDB usando Python. Ora, immergiamoci nei dettagli.
2. Configurazione dell’Ambiente (Installazione di MariaDB & Python)
Che cos’è MariaDB?
MariaDB è un sistema di gestione di database relazionali open‑source (RDBMS) ampiamente utilizzato come successore di MySQL. Pur mantenendo un’alta compatibilità con MySQL, MariaDB ha migliorato le prestazioni e aggiunto nuove funzionalità.
Strumenti richiesti
Per lavorare con MariaDB in Python, devi preparare i seguenti strumenti:
- Python (versione 3.x o successiva consigliata)
- MariaDB (server)
- Connettore Python per MariaDB (la libreria mariadb)
Come installare MariaDB (per OS)
Per Windows
- Scarica l’installer di MariaDB dal sito ufficiale .
- Esegui l’installer e segui le istruzioni per completare l’installazione.
- Dopo l’installazione, verifica che MariaDB funzioni eseguendo il comando seguente:
mysql -u root -p
- Se riesci ad accedere con successo, l’installazione è completa.
Per Mac
Su Mac puoi installare facilmente MariaDB usando Homebrew.
- Se Homebrew non è installato, installalo con il comando seguente:
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
- Installa MariaDB:
brew install mariadb
- Avvia MariaDB:
brew services start mariadb
- Verifica l’installazione:
mysql -u root -p
Per Linux (Ubuntu)
- Aggiorna l’elenco dei pacchetti e installa MariaDB:
sudo apt update sudo apt install mariadb-server mariadb-client
- Avvia MariaDB:
sudo systemctl start mariadb
- Abilita MariaDB (avvio automatico all’avvio del sistema):
sudo systemctl enable mariadb
- Esegui lo script di installazione sicura:
sudo mysql_secure_installation
Questo ti permette di impostare la password di root e rimuovere le impostazioni predefinite non necessarie.
Installazione di Python e della libreria richiesta
Per integrare MariaDB con Python, devi installare la libreria mariadb.
- Installa la libreria
mariadbusandopip:pip install mariadb
- Verifica l’installazione:
import mariadb print("The MariaDB library was installed successfully.")
Se non si verifica alcun errore, l’installazione è avvenuta con successo.
Ora la configurazione dell’ambiente per usare Python con MariaDB è completa. Successivamente spiegheremo come connettersi a MariaDB da Python. 
3. Connessione a MariaDB
Come connettersi a MariaDB con Python
Importa la libreria richiesta
Per connettersi a MariaDB, importa la libreria Python mariadb.
import mariadb
Codice base per connettersi al database
Il codice seguente mostra il modo base per connettersi a MariaDB usando 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!")
# Crea un cursore
cursor = conn.cursor()
# Se la connessione ha successo, chiudila
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"Errore verificato: {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
# Connessione al database
config = {
"host": "localhost",
"user": "root",
"password": "password",
"database": "sample_db"
}
try:
conn = mariadb.connect(**config)
cursor = conn.cursor()
# SQL per la creazione della tabella
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("Tabella 'users' creata.")
cursor.close()
conn.close()
except mariadb.Error as e:
print(f"Errore verificato: {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
# Impostazioni di connessione al database
config = {
"host": "localhost",
"user": "root",
"password": "password",
"database": "sample_db"
}
try:
conn = mariadb.connect(**config)
cursor = conn.cursor()
# Inserisci dati
insert_query = "INSERT INTO users (name, email) VALUES (?, ?)"
data = ("Alice", "alice@example.com")
cursor.execute(insert_query, data)
# Salva le modifiche
conn.commit()
print("Dati inseriti con successo!")
cursor.close()
conn.close()
except mariadb.Error as e:
print(f"Si è verificato un errore: {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()
# Recupera dati
select_query = "SELECT id, name, email FROM users"
cursor.execute(select_query)
# Visualizza i dati recuperati
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"Si è verificato un errore: {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()
# Aggiorna dati
update_query = "UPDATE users SET name = ? WHERE email = ?"
data = ("Alice Smith", "alice@example.com")
cursor.execute(update_query, data)
# Salva le modifiche
conn.commit()
print("Dati aggiornati con successo!")
cursor.close()
conn.close()
except mariadb.Error as e:
print(f"Si è verificato un errore: {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()
# Elimina dati
delete_query = "DELETE FROM users WHERE email = ?"
data = ("alice@example.com",)
cursor.execute(delete_query, data)
# Salva le modifiche
conn.commit()
print("Dati eliminati con successo!")
cursor.close()
conn.close()
except mariadb.Error as e:
print(f"Si è verificato un errore: {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)
Quando si lavora con un database, è importante utilizzare transazioni per mantenere l’integrità dei dati.
In particolare, la capacità di ripristinare i dati al loro stato originale (rollback) quando si verifica un errore durante l’elaborazione è essenziale per mantenere la coerenza.
In questa sezione spiegheremo come gestire le transazioni in MariaDB usando Python.
Che cos’è una transazione?
Una transazione è un meccanismo che raggruppa una serie di operazioni sul database in un’unica unità, conferma tutte le modifiche se ogni processo ha successo e annulla tutte le modifiche se si verifica un errore.
Caratteristiche delle transazioni
- Proprietà ACID
- Atomicità : tutte le operazioni o si completano con successo o nessuna viene applicata.
- Coerenza : l’integrità dei dati è mantenuta.
- Isolamento : le transazioni concorrenti non interferiscono tra loro.
- Durabilità : una volta confermate, le modifiche sono salvate permanentemente.
Operazioni di base delle transazioni (COMMIT e ROLLBACK)
Le transazioni MariaDB possono essere controllate con i seguenti comandi:
| Command | Description |
|---|---|
START TRANSACTION; | Begin a transaction |
COMMIT; | Commit changes (cannot be undone after commit) |
ROLLBACK; | Cancel changes (restore the original state) |
Utilizzare le transazioni in Python
Di seguito è riportato un esempio base di gestione delle transazioni MariaDB usando Python.
Gestire più operazioni all’interno di una singola transazione
Il codice seguente tratta multiple operazioni di inserimento come un’unica transazione e conferma solo se tutte le operazioni hanno successo.
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
Punti chiave
- Usa
conn.start_transaction()per avviare una transazione.- Usa
conn.commit()per finalizzare le modifiche (non può essere annullato dopo il commit).- Se si verifica un errore, usa
conn.rollback()per annullare le modifiche e ripristinare lo stato originale.
Gestione degli errori basata su transazioni
Gli errori possono verificarsi durante le operazioni sul database.
Ad esempio, un indirizzo email duplicato (violazione del vincolo UNIQUE) o un timeout del server possono verificarsi.
Gestione delle transazioni con gestione degli errori
Il codice seguente aggiunge una logica per annullare le modifiche e ripristinare lo stato originale se si verifica un errore durante l’elaborazione.
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}")
Riepilogo
In questa sezione abbiamo spiegato le basi delle transazioni e come implementarle in Python.
- L’importanza delle transazioni e delle proprietà ACID
- Come usare
commit()erollback()in Python - Gestione delle transazioni combinata con la gestione degli errori
7. Gestione degli errori (Errori comuni e soluzioni)
Quando si lavora con MariaDB in Python, possono verificarsi errori.
In particolare, errori di connessione al database, errori di sintassi SQL e errori di integrità dei dati sono comuni, quindi è importante comprendere le loro cause e le soluzioni.
In questa sezione, presentiamo le cause degli errori comuni e come risolverli.
Access denied for user (Authentication error)
Error message
mariadb.OperationalError: Access denied for user 'root'@'localhost' (using password: YES)
Cause
- Il nome utente o la password non sono corretti
- L’utente MariaDB non dispone dei privilegi appropriati
Solution
- Accedi a MariaDB e verifica i privilegi dell’utente
mysql -u root -p
- Concedi i privilegi all’utente
GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' IDENTIFIED BY 'password' WITH GRANT OPTION; FLUSH PRIVILEGES;
- Riavvia MariaDB
sudo systemctl restart mariadb
Can't connect to MySQL server on 'localhost' (Connection error)
Error message
mariadb.OperationalError: Can't connect to MySQL server on 'localhost' (10061)
Cause
- Il server MariaDB non è in esecuzione
- L’impostazione
hostè errata
Solution
- Verifica se il server MariaDB è in esecuzione
sudo systemctl status mariadb
- Se il server è fermo, avvialo
sudo systemctl start mariadb
- Abilita l’avvio automatico del server
sudo systemctl enable mariadb
Unknown database 'sample_db' (Database does not exist)
Error message
mariadb.ProgrammingError: Unknown database 'sample_db'
Cause
- Il database specificato non esiste
- C’è un errore di battitura nel nome del database
Solution
- Controlla l’elenco dei database
SHOW DATABASES;
- Crea il database se non esiste
CREATE DATABASE sample_db;
Table doesn't exist (Table does not exist)
Error message
mariadb.ProgrammingError: Table 'sample_db.users' doesn't exist
Cause
- La tabella specificata non esiste
- Il database non è stato selezionato usando
USE sample_db;
Solution
- Controlla l’elenco delle tabelle
SHOW TABLES;
- Crea la tabella se non esiste
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 (Duplicate data error)
Error message
mariadb.IntegrityError: Duplicate entry 'alice@example.com' for key 'users.email'
Cause
- La colonna
emailha un vincoloUNIQUE, quindi non è possibile inserire valori duplicati
Solution
- Verifica la presenza di duplicati prima di inserire i dati
- Usa
ON DUPLICATE KEY UPDATE
Codice Python per prevenire i duplicati
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.")
Oppure usa 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 (Parameter count mismatch)
Error message
mariadb.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 2, and there are 1 supplied.
Cause
- Il numero di parametri richiesti dall’istruzione SQL non corrisponde al numero di argomenti forniti
Solution
- Assicurati che il numero di segnaposti corrisponda al numero di parametri
Codice errato
cursor.execute("INSERT INTO users (name, email) VALUES (?, ?)", ("Alice"))
Codice corretto
cursor.execute("INSERT INTO users (name, email) VALUES (?, ?)", ("Alice", "alice@example.com"))
Sommario
In questa sezione, abbiamo spiegato gli errori comuni che si verificano quando si lavora con MariaDB in Python e come risolverli.
Access denied for user(Errore di autenticazione)Can't connect to MySQL server(Errore di connessione)Unknown database(Database inesistente)Table doesn't exist(Tabella inesistente)Duplicate entry(Errore di dati duplicati)Incorrect number of bindings(Numero di parametri non corrispondente)
8. Conclusione
In questo articolo, abbiamo spiegato come lavorare con MariaDB usando Python, dai concetti di base a quelli più avanzati.
Comprendendo le operazioni fondamentali del database e implementando correttamente la gestione degli errori e delle transazioni, è possibile eseguire operazioni sui dati in modo più sicuro ed efficiente.
Riepilogo dell’articolo
Configurazione dell’ambiente
- Come installare MariaDB (Windows / Mac / Linux)
- Come installare la libreria connettore MariaDB (mariadb) per Python
Connessione a MariaDB
- Metodi di connessione al database di base
- Connessioni sicure usando variabili d’ambiente
- Soluzioni per errori di connessione comuni
Creazione di database e tabelle
- Creazione di database (SQL / Python)
- Creazione di tabelle e scelta dei tipi di dati
- Verifica e rimozione delle tabelle esistenti
Operazioni CRUD (Create, Read, Update, Delete)
- Operazioni di base sui dati usando Python
- Uso di placeholder per prevenire l’iniezione SQL
- Gestione corretta degli errori
Transazioni e rollback
- L’importanza delle transazioni (proprietà ACID)
- Come ripristinare i dati in caso di errore (rollback)
- Gestire le transazioni manualmente disabilitando AutoCommit
Gestione degli errori (Errori comuni e soluzioni)
- Errori di autenticazione (
Access denied for user) - Errori di connessione (
Can't connect to MySQL server) - Errori di database o tabella non trovati
- Errori di dati duplicati (
Duplicate entry) - Gestione dei deadlock e implementazione della logica di retry
Punti chiave quando si combinano Python e MariaDB
- Usa i placeholder
cursor.execute("INSERT INTO users (name, email) VALUES (?, ?)", ("Alice", "alice@example.com"))
→ Usa variabili bind invece di incorporarle direttamente nelle istruzioni SQL per prevenire l’iniezione SQL.
- Gestisci le transazioni correttamente
- Usa
conn.commit()per confermare esplicitamente le modifiche. - Usa
conn.rollback()in caso di errore per mantenere l’integrità dei dati.
- Implementa una gestione completa degli errori
- Usa blocchi
try-exceptper catturare potenziali errori in anticipo. - Prepara strategie di gestione specifiche per errori come
OperationalErroreIntegrityError.
- Considera le prestazioni
- Inserimenti in blocco (inserire più record contemporaneamente)
- Indicizzazione corretta (migliorare le prestazioni di ricerca)
Risorse per approfondire
Se desideri approfondire la tua comprensione dell’integrazione tra Python e MariaDB, considera le seguenti risorse:
Documentazione ufficiale
Contenuti di apprendimento correlati
Libri consigliati
- SQL, 2nd Edition: Database Operations from Scratch – Impara a fondo i fondamenti di SQL
- Effective Python: 90 Specific Ways to Improve Your Python Programs – Impara le migliori pratiche di Python
Sommario
Integrando MariaDB con Python, è possibile abilitare la gestione dei dati basata su script e l’automazione.
Implementando non solo le operazioni CRUD di base ma anche una corretta gestione degli errori e delle transazioni, è possibile costruire un sistema più sicuro ed efficiente.
Come prossimo passo, considera di approfondire la gestione efficiente dei dati e l’integrazione delle API per applicare le tue conoscenze a operazioni pratiche sui database.


