martedì 1 novembre 2011

[VB.NET] Connessione ad Sql Server Express

Descrizione :
Un esempio semplice di connessione e lettura dati da tabella su Sql Server 2008 R2 Express.

+ Articolo :

L'esempio che segue è liberamente dedicato soprattutto agli ex-VB6 che vedo spesso avere qualche problema di adattamento alla "nuova" filosofia di connessione e lettura dati usando ADO.NET e il relativo provider di dati d'elezione per Sql Server : Spazio dei nomi System.Data.SqlClient ()

Anzitutto il DB : si tratta di Sql Server 2008 R2 Express + relativo Tool di amministrazione "Microsoft SQL Server Management Studio".
Tralascio le informazioni su installazione/configurazione del server di database, e mi soffermo solo su quanto è essenziale alla replica del presente esempio.

Il DB di test è testdatabase, e la tabella di test è tabellatest.

--> Struttura di tabellatest :
id - int [ PK ]
nome - varchar
cognome - varchar
numpratiche - int

La lettura dati viene fatta in due modalità : "Trusted Connection" e "Standard Security", per mostrare due differenti approcci e relative stringhe di connessione.
Queste ed altre tipologie di connessione/sicurezza sono reperibili sul celeberrimo sito connectionstrings.com ...

1. Trusted Connection :
Data Source = viene passato indirizzo/nome macchina, e visto che la versione è la Express sarà : NOMEMACCHINA\SQLEXPRESS
Initial Catalog = nome del DB --> testdatabase
Integrated Security = SSPI

In pratica viene usato il login principale di amministrazione, ossia quello che in fase di installazione del server è il system/database administrator.

2. Standard Security :
Per utilizzare questa stringa di connessione ho usato un nuovo utente, definito in Sql Server allo scopo, con modalità di autenticazione "Autenticazione di Sql Server".
Oltre a dare pieni permessi sul DB testdatabase, è importante verificare da Management Studio che :
Proprietà Server / Sicurezza / Autenticazione server = Autenticazione di SQL Server e di Windows.

Il nuovo utente è :
User : marcogg
Password : abc

Perciò :
Data Source = NOMEMACCHINA\SQLEXPRESS
Initial Catalog = nome del DB --> testdatabase
User Id = marcogg
Password = abc

--> Form di Test :
Per rendere il tutto ancora più interessante agli occhi di un ex-VB6 tipico, così attaccato al buon vecchio Recordset, ho previsto un ciclo di lettura mediante DataReader, la creazione dinamica di Oggetti della Classe "Persona" ( quindi 1 Record = 1 Persona ), l'aggiunta ad un insieme "Persone", e infine la visualizzazione dei risultati in un DataGridView "DGV".

--> Codice per la Classe Persona :

Public Class Persona
 
    Private m_id As Integer
    Private m_nome As String
    Private m_cognome As String
    Private m_numpratiche As Integer
 
    Public Property Id() As Integer
        Get
            Return m_id
        End Get
        Set(ByVal value As Integer)
            m_id = value
        End Set
    End Property
 
    Public Property Nome() As String
        Get
            Return m_nome
        End Get
        Set(ByVal value As String)
            m_nome = value
        End Set
    End Property
 
    Public Property Cognome() As String
        Get
            Return m_cognome
        End Get
        Set(ByVal value As String)
            m_cognome = value
        End Set
    End Property
 
    Public Property NumPratiche As Integer
        Get
            Return m_numpratiche
        End Get
        Set(ByVal value As Integer)
            m_numpratiche = value
        End Set
    End Property
 
End Class

--> Codice FormMain :
Public Class FormMain
 
    Private Persone As New List(Of Persona)
 
    Private nomeServer As String = "NOMEMACCHINA\SQLEXPRESS"
    Private nomeDB As String = "testdatabase"
    Private userId As String = "marcogg" 
    Private pwd As String = "abc"
 
    Private Sub cmd_selectdr_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmd_selectdr.Click
 
        Persone.Clear()
 
        'Trusted Connection
        'Dim strCN As String = "Data Source=" & nomeServer & ";Initial Catalog=" & nomeDB & _
        '                      ";Integrated Security=SSPI;"
 
        'Standard Security
        Dim strCN As String = "Data Source=" & nomeServer & ";Initial Catalog=" & nomeDB & _
                              ";User Id=" & userId & ";Password=" & pwd & ";"
 
        Dim CN As New SqlClient.SqlConnection(strCN)
        Dim strSql As String = "SELECT * FROM tabellatest"
        Dim CMD As New SqlClient.SqlCommand(strSql, CN)
 
        CN.Open()
        Dim RDR As SqlClient.SqlDataReader = CMD.ExecuteReader()
 
        Dim P As Persona
 
        While (RDR.Read())
 
            P = New Persona
 
            P.Id = RDR("id")
            P.Nome = RDR("nome")
            P.Cognome = RDR("cognome")
            P.NumPratiche = RDR("numpratiche")
 
            Persone.Add(P)
 
        End While
 
        DGV.DataSource = Persone
 
        RDR.Close()
        CN.Close()
 
    End Sub
 
End Class

Come si può notare è possibile testare velocemente le due modalità Trusted e Standard, semplicemente commentando l'una o l'altra alternativamente.

--> SqlConnectionStringBuilder :
Creare e gestire stringhe di connessione concatenando nomi-chiave e relativi valori non è certo la cosa più elegante che si possa fare.
Un passo in avanti è sicuramente l'uso della Classe SqlConnectionStringBuilder.

Per brevità, riporto solo il codice-pulsante dell'esempio precedente, ma con l'utilizzo della SqlConnectionStringBuilder.
E' possibile notare come i valori-chiave possano essere passati direttamente o usando le apposite Proprietà ( soluzione che preferisco ).

        Persone.Clear()

        '--> Costruzione Stringa di Connessione con SqlConnectionStringBuilder

        'Trusted Connection 1
        Dim sqlCnSb As New SqlClient.SqlConnectionStringBuilder
        sqlCnSb.DataSource = nomeServer
        sqlCnSb.InitialCatalog = nomeDB
        sqlCnSb.IntegratedSecurity = True

        '--> Oppure

        'Trusted Connection 2
        'Dim sqlCnSb As New SqlClient.SqlConnectionStringBuilder
        'sqlCnSb("Data Source") = nomeServer
        'sqlCnSb("Initial Catalog") = nomeDB
        'sqlCnSb("Integrated Security") = True

        '--> Oppure

        'Standard Security 1
        'Dim sqlCnSb As New SqlClient.SqlConnectionStringBuilder
        'sqlCnSb.DataSource = nomeServer
        'sqlCnSb.InitialCatalog = nomeDB
        'sqlCnSb.UserID = userId
        'sqlCnSb.Password = pwd

        '--> Oppure

        'Standard Security 2
        'Dim sqlCnSb As New SqlClient.SqlConnectionStringBuilder
        'sqlCnSb("Data Source") = nomeServer
        'sqlCnSb("Initial Catalog") = nomeDB
        'sqlCnSb("User Id") = userId
        'sqlCnSb("Password") = pwd

        '--> Fine Costruzione Stringa di Connessione con SqlConnectionStringBuilder

        Dim CN As New SqlClient.SqlConnection(sqlCnSb.ConnectionString)
        Dim strSql As String = "SELECT * FROM tabellatest"
        Dim CMD As New SqlClient.SqlCommand(strSql, CN)

        CN.Open()
        Dim RDR As SqlClient.SqlDataReader = CMD.ExecuteReader()

        Dim P As Persona

        While (RDR.Read())

            P = New Persona

            P.Id = RDR("id")
            P.Nome = RDR("nome")
            P.Cognome = RDR("cognome")
            P.NumPratiche = RDR("numpratiche")

            Persone.Add(P)

        End While

        DGV.DataSource = Persone

        RDR.Close()
        CN.Close()

+ Fine Articolo.

Un Click su "Mi Piace" è il modo migliore per ringraziare l'autore di questo articolo.



0 commenti:

Posta un commento

 
Design by Free WordPress Themes Modificato da MarcoGG