* Conoscenza del computer >> sistemi >  >> Windows 2016

Tutorial SQL e VBA per Microsoft Access

Integrare SQL e VBA in Access per gestire database

SQL (Structured Query Language) è il linguaggio standard per interrogare e manipolare database relazionali. VBA (Visual Basic for Applications) è il linguaggio di programmazione di Microsoft Office per automatizzare task e creare logiche personalizzate. Microsoft Access combina entrambi: usa SQL per i dati e VBA per l'automazione.

Attraverso l'editor VBA di Access (accessibile da Strumenti database > Visual Basic) puoi connetterti al database, eseguire query, inserire, aggiornare ed eliminare record combinando la potenza dichiarativa di SQL con la flessibilità procedurale di VBA.

Esempio pratico: operazioni CRUD con ADO

Il seguente codice VBA mostra come dichiarare variabili di connessione e recordset, stabilire la connessione a un database Access (.mdb) e definire le istruzioni SQL per le quattro operazioni fondamentali.

1. Aprire l'editor VBA e creare un modulo

  • In Access: Strumenti database > Visual Basic
  • Inserisci > Modulo

2. Codice completo (spiegato)

Sub SQLTutorial()
    ' Dichiarazione variabili
    Dim Conn As ADODB.Connection
    Dim rsSelect As ADODB.Recordset, rsDelete As ADODB.Recordset
    Dim rsInsert As ADODB.Recordset, rsUpdate As ADODB.Recordset
    Dim strSelectQuery As String, strDeleteQuery As String
    Dim strInsertQuery As String, strUpdateQuery As String

    ' Connessione al database
    Set Conn = New ADODB.Connection
    With Conn
        .ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
                           "Data Source=C:\Documents\SampleDatabase.mdb"
        .Open
    End With

    ' --- SELECT: leggere dati ---
    ' Tutti i campi per cognome Smith
    strSelectQuery = "SELECT * FROM tblCustomers WHERE LastName = 'Smith'"
    ' Solo campi specifici
    ' strSelectQuery = "SELECT FirstName, LastName FROM tblCustomers WHERE LastName = 'Smith'"

    ' --- DELETE: eliminare record ---
    strDeleteQuery = "DELETE FROM tblCustomers WHERE LastName = 'Smith'"

    ' --- INSERT: aggiungere nuovo record ---
    ' Ordine valori = ordine colonne nella tabella
    strInsertQuery = "INSERT INTO tblCustomers VALUES ('John', 'Smith', '123 Main Street', 'Cleveland', 'Ohio')"

    ' --- UPDATE: modificare record esistenti ---
    strUpdateQuery = "UPDATE tblCustomers SET LastName = 'Jones', FirstName = 'Jim' WHERE LastName = 'Smith'"

    ' Esecuzione query e gestione recordset
    Set rsSelect = New ADODB.Recordset
    With rsSelect
        Set .ActiveConnection = Conn
        .CursorType = adOpenStatic
        .Source = strSelectQuery
        .Open
    End With

    Set rsDelete = New ADODB.Recordset
    With rsDelete
        Set .ActiveConnection = Conn
        .Source = strDeleteQuery
        .Open
    End With

    Set rsInsert = New ADODB.Recordset
    With rsInsert
        Set .ActiveConnection = Conn
        .CursorType = adOpenStatic
        .Source = strInsertQuery
        .Open
    End With

    Set rsUpdate = New ADODB.Recordset
    With rsUpdate
        Set .ActiveConnection = Conn
        .CursorType = adOpenStatic
        .Source = strUpdateQuery
        .Open
    End With

    ' Qui puoi lavorare con i dati in rsSelect (es. popolare form, report)
    ' Pulizia
    rsSelect.Close: rsDelete.Close: rsInsert.Close: rsUpdate.Close
    Conn.Close
    Set rsSelect = Nothing: Set rsDelete = Nothing
    Set rsInsert = Nothing: Set rsUpdate = Nothing
    Set Conn = Nothing
End Sub

Punti chiave

  • Reference ADO: In VBE: Strumenti > Riferimenti > spunta Microsoft ActiveX Data Objects x.x Library.
  • Wildcard * in SELECT significa "tutte le colonne".
  • WHERE filtra i record interessati.
  • Ordine valori in INSERT deve corrispondere esattamente all'ordine delle colonne nella tabella.
  • Chiusura risorse: chiudi sempre recordset e connessione per evitare memory leak.

Questa base ti permette di costruire applicazioni Access potenti: form collegati a dati, report dinamici, procedure di import/export automatizzate.

Windows 2016