Guest User

Untitled

a guest
Aug 16th, 2018
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.92 KB | None | 0 0
  1. VB2010: Connect to SQL Server 2008
  2. Imports System.Data
  3. Imports System.Data.SqlClient
  4.  
  5. Public Class Form1
  6.  
  7. Dim SQLConn As SqlClient.SqlConnection
  8.  
  9. Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
  10. Dim i As Integer
  11. Dim connectionstring As String
  12. connectionstring = "Data Source=MySQLServerMyInstance;Database=MyDatabase;Integrated Security=true;"
  13.  
  14. Try
  15. SQLConn = New SqlConnection(connectionstring)
  16. SQLConn.Open()
  17. Catch ex As Exception
  18. MsgBox(ex.Message & " Error Connecting to database!", MsgBoxStyle.Critical)
  19. Exit Sub
  20. End Try
  21. Dim da As SqlDataAdapter
  22. da = New SqlDataAdapter("SELECT * from DR_Users", SQLConn)
  23. Dim dt As DataTable
  24. da.Fill(dt)
  25. For i = 0 To dt.Rows.Count - 1
  26. Dim dr As DataRow = dt.Rows(i)
  27. Debug.Print(dr.Item("UserId").ToString)
  28. Next
  29.  
  30. End Sub
  31. End Class
  32.  
  33. Public Property ServerName() As String
  34. Public Property DatabaseName() As String
  35. Public Property Login() As String
  36. Public Property Password() As String
  37.  
  38. Private Function SqlConn(Optional timeout As Integer = 0) As String
  39. ' Initialize the connection string builder for the
  40. ' underlying provider.
  41. Dim sqlBuilder As New SqlClient.SqlConnectionStringBuilder()
  42.  
  43. ' Set the properties for the data source.
  44. sqlBuilder.DataSource = _serverName
  45. sqlBuilder.InitialCatalog = _databaseName
  46. sqlBuilder.IntegratedSecurity = False
  47. sqlBuilder.MultipleActiveResultSets = True 'to avoid exception if a query uses anothe rquery internal
  48.  
  49. sqlBuilder.UserID = _Login
  50. sqlBuilder.Password = _Password
  51. If timeout > 0 Then
  52. sqlBuilder.ConnectTimeout = timeout
  53. End If
  54.  
  55. Return sqlBuilder.ToString
  56. End Function
  57.  
  58. Using sqlConn As New SqlClient.SqlConnection(sqlConnString)
  59. sqlConn.Open()
  60. [...]
  61. sqlConn.Close()
  62. End Using
Add Comment
Please, Sign In to add comment