Jak pożenić VB z Microsoft SQL Server

Czasem się zdarza,  że trzeba dokonać rzeczy dziwacznej – a mianowicie połączyć się z poziomu (Excela np.) poprzez Visual Basic do bazy Microsoft SQL Server.

Jak dokonać tego cudu?

Z pomocą przyjdzie nam taki kawałek kodu:

 

’Imports System.Data.SqlClient

        Dim con As New SqlClient.SqlConnection
        Dim strCon As String = „Data Source=SERVERNAME\SQLEXPRESS;Initial Catalog=SQLEXPRESS;Integrated Security=SSPI;Connection Timeout=10;” 'NT Authentication
        'For SQL Authentication Dim strCon As String = „Data Source=SERVERNAME\SQLEXPRESS;Initial Catalog=DATABASENAME;User ID=USERNAME;Password=PASSWORD;Connection Timeout=50;”
        Dim strCommand As String = „SELECT * FROM TABLE”
        Dim command As SqlCommand
        Dim da As SqlDataAdapter
        Dim dt As New DataTable
        Try
            con.ConnectionString = strCon
            command = New SqlCommand(strCommand, con)
            command.CommandTimeout = 3000

            da = New SqlDataAdapter(command)
            da.Fill(dt)
            MsgBox(dt.Rows.Count.ToString())

            'FOR INSERT, UPDATE, DELETE, USE BELOW

            'Dim count as Integer = command.ExecuteNonQuery()

            'count is the affected row number

        Catch ex As Exception
            MessageBox.Show(ex.Message, „Error”)
        Finally
            If con.State = ConnectionState.Open Then
                con.Close()
            End If
        End Try

 

Aby dobrze dopasować ConnectionString posłużymy się taką ściągą:

https://www.connectionstrings.com/sql-server/

 

Dodaj komentarz

Twój adres e-mail nie zostanie opublikowany.