Guida a SQLite: Il Database in un Solo File

SQLite è il motore di database relazionale più diffuso al mondo, ma funziona in modo radicalmente diverso rispetto a sistemi complessi come MySQL o PostgreSQL. La sua caratteristica principale è l’architettura serverless: non richiede l’installazione di un server in background, configurazioni di rete, né la gestione di utenti e password.

L’intero database, comprensivo di tabelle, indici e dati, è racchiuso all’interno di un singolo file testuale sul tuo disco fisso (solitamente salvato con estensione .sqlite o .db).

Sqlite3 il database racchiuso in un solo file.

A Cosa Potrebbe Servire un Database su Singolo File?

Essendo leggero e portatile, SQLite non è progettato per gestire le migliaia di scritture simultanee di un enorme e-commerce, ma eccelle in tantissimi altri scenari pratici:

  • Script e Web Scraper: È perfetto per script di automazione che devono scansionare pagine web, raccogliere dati e memorizzarli in modo strutturato, garantendo che le informazioni non vadano perse in caso di interruzione improvvisa.
  • Sviluppo e Prototipazione: Permette di testare rapidamente la logica di backend e le operazioni CRUD di un’applicazione lavorando in locale, senza dover configurare un database esterno.
  • Applicazioni Desktop e Mobile: È il motore predefinito di Android, iOS e di moltissimi programmi desktop per salvare le preferenze, i log e i dati dell’utente.

Come Utilizzarlo: Un Esempio in Python

L’integrazione di SQLite con molti linguaggi di programmazione è nativa. In Python non è nemmeno necessario installare pacchetti esterni tramite pip. Ecco un esempio base che illustra come connettersi, creare una tabella, inserire dati e leggerli:

import sqlite3

# 1. Si collega al file (se il file non esiste, lo crea automaticamente)
connessione = sqlite3.connect("miodatabase.sqlite")
cursore = connessione.cursor()

# 2. Crea una tabella
cursore.execute("""
    CREATE TABLE IF NOT EXISTS utenti (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        nome TEXT NOT NULL,
        ruolo TEXT
    )
""")

# 3. Inserisce un record
cursore.execute("INSERT INTO utenti (nome, ruolo) VALUES (?, ?)", ("Mario Rossi", "Amministratore"))
connessione.commit()

# 4. Rilegge e stampa i dati
cursore.execute("SELECT * FROM utenti")
print(cursore.fetchall())

# 5. Chiude la connessione
connessione.close()

Strumenti Semplici per Consultare il File SQLite

Una volta che il tuo codice ha generato il file .sqlite, non devi per forza usare script di programmazione per analizzarne il contenuto. Esistono ottimi software visivi gratuiti:

1. DB Browser for SQLite (Ideale per iniziare)

È lo strumento visivo più semplice e leggero, disponibile sia per Windows che per Linux (Ubuntu). Ti permette di aprire il tuo file .sqlite con un click, sfogliare i dati in formato tabellare simile a Excel, modificare manualmente le celle e testare query SQL.

2. DBeaver

Uno strumento open-source più avanzato e multipiattaforma. Funziona in modo eccellente su ambienti Linux e Windows. È altamente consigliato se, oltre a SQLite, ti capita di lavorare anche con database più grandi, in quanto ti offre un’unica interfaccia unificata.

3. La Riga di Comando (CLI)

Se usi regolarmente Ubuntu o una distribuzione Linux e preferisci muoverti da terminale, puoi esplorare il database in modo nativo.

Ti basta installare il pacchetto base

sudo apt-get install sqlite

e digitare sqlite3 miodatabase.sqlite. Da quel momento, potrai lanciare comandi rapidi come .tables per elencare le tabelle o scrivere direttamente le tue SELECT.

Qui di seguito troverai i comandi per usare sqlite3 da command line.

sqlite> .help
.archive ...             Manage SQL archives
.auth ON|OFF             Show authorizer callbacks
.backup ?DB? FILE        Backup DB (default "main") to FILE
.bail on|off             Stop after hitting an error.  Default OFF
.cd DIRECTORY            Change the working directory to DIRECTORY
.changes on|off          Show number of rows changed by SQL
.check GLOB              Fail if output since .testcase does not match
.clone NEWDB             Clone data into NEWDB from the existing database
.connection [close] [#]  Open or close an auxiliary database connection
.databases               List names and files of attached databases
.dbconfig ?op? ?val?     List or change sqlite3_db_config() options
.dbinfo ?DB?             Show status information about the database
.dump ?OBJECTS?          Render database content as SQL
.echo on|off             Turn command echo on or off
.eqp on|off|full|...     Enable or disable automatic EXPLAIN QUERY PLAN
.excel                   Display the output of next command in spreadsheet
.exit ?CODE?             Exit this program with return-code CODE
.expert                  EXPERIMENTAL. Suggest indexes for queries
.explain ?on|off|auto?   Change the EXPLAIN formatting mode.  Default: auto
.filectrl CMD ...        Run various sqlite3_file_control() operations
.fullschema ?--indent?   Show schema and the content of sqlite_stat tables
.headers on|off          Turn display of headers on or off
.help ?-all? ?PATTERN?   Show help text for PATTERN
.import FILE TABLE       Import data from FILE into TABLE
.indexes ?TABLE?         Show names of indexes
.limit ?LIMIT? ?VAL?     Display or change the value of an SQLITE_LIMIT
.lint OPTIONS            Report potential schema issues.
.load FILE ?ENTRY?       Load an extension library
.log FILE|on|off         Turn logging on or off.  FILE can be stderr/stdout
.mode MODE ?OPTIONS?     Set output mode
.nonce STRING            Suspend safe mode for one command if nonce matches
.nullvalue STRING        Use STRING in place of NULL values
.once ?OPTIONS? ?FILE?   Output for the next SQL command only to FILE
.open ?OPTIONS? ?FILE?   Close existing database and reopen FILE
.output ?FILE?           Send output to FILE or stdout if FILE is omitted
.parameter CMD ...       Manage SQL parameter bindings
.print STRING...         Print literal STRING
.progress N              Invoke progress handler after every N opcodes
.prompt MAIN CONTINUE    Replace the standard prompts
.quit                    Stop interpreting input stream, exit if primary.
.read FILE               Read input from FILE or command output
.recover                 Recover as much data as possible from corrupt db.
.restore ?DB? FILE       Restore content of DB (default "main") from FILE
.save ?OPTIONS? FILE     Write database to FILE (an alias for .backup ...)
.scanstats on|off|est    Turn sqlite3_stmt_scanstatus() metrics on or off
.schema ?PATTERN?        Show the CREATE statements matching PATTERN
.separator COL ?ROW?     Change the column and row separators
.session ?NAME? CMD ...  Create or control sessions
.sha3sum ...             Compute a SHA3 hash of database content
.shell CMD ARGS...       Run CMD ARGS... in a system shell
.show                    Show the current values for various settings
.stats ?ARG?             Show stats or turn stats on or off
.system CMD ARGS...      Run CMD ARGS... in a system shell
.tables ?TABLE?          List names of tables matching LIKE pattern TABLE
.timeout MS              Try opening locked tables for MS milliseconds
.timer on|off            Turn SQL timer on or off
.trace ?OPTIONS?         Output each SQL statement as it is run
.version                 Show source, library and compiler versions
.vfsinfo ?AUX?           Information about the top-level VFS
.vfslist                 List all available VFSes
.vfsname ?AUX?           Print the name of the VFS stack
.width NUM1 NUM2 ...     Set minimum column widths for columnar output

Lascia un commento