Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- VB2010: Connect to SQL Server 2008
- Imports System.Data
- Imports System.Data.SqlClient
- Public Class Form1
- Dim SQLConn As SqlClient.SqlConnection
- Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
- Dim i As Integer
- Dim connectionstring As String
- connectionstring = "Data Source=MySQLServerMyInstance;Database=MyDatabase;Integrated Security=true;"
- Try
- SQLConn = New SqlConnection(connectionstring)
- SQLConn.Open()
- Catch ex As Exception
- MsgBox(ex.Message & " Error Connecting to database!", MsgBoxStyle.Critical)
- Exit Sub
- End Try
- Dim da As SqlDataAdapter
- da = New SqlDataAdapter("SELECT * from DR_Users", SQLConn)
- Dim dt As DataTable
- da.Fill(dt)
- For i = 0 To dt.Rows.Count - 1
- Dim dr As DataRow = dt.Rows(i)
- Debug.Print(dr.Item("UserId").ToString)
- Next
- End Sub
- End Class
- Public Property ServerName() As String
- Public Property DatabaseName() As String
- Public Property Login() As String
- Public Property Password() As String
- Private Function SqlConn(Optional timeout As Integer = 0) As String
- ' Initialize the connection string builder for the
- ' underlying provider.
- Dim sqlBuilder As New SqlClient.SqlConnectionStringBuilder()
- ' Set the properties for the data source.
- sqlBuilder.DataSource = _serverName
- sqlBuilder.InitialCatalog = _databaseName
- sqlBuilder.IntegratedSecurity = False
- sqlBuilder.MultipleActiveResultSets = True 'to avoid exception if a query uses anothe rquery internal
- sqlBuilder.UserID = _Login
- sqlBuilder.Password = _Password
- If timeout > 0 Then
- sqlBuilder.ConnectTimeout = timeout
- End If
- Return sqlBuilder.ToString
- End Function
- Using sqlConn As New SqlClient.SqlConnection(sqlConnString)
- sqlConn.Open()
- [...]
- sqlConn.Close()
- End Using
Add Comment
Please, Sign In to add comment