VB.Net - Connect to SqlServer Database

This code snippet shows how to connect to an SqlServer database and read values using the SqlDataReader class.
  1. 'Default.aspx.vb
  2.  
  3. Imports System.Data
  4. Imports System.Data.SqlClient
  5.  
  6. Partial Class _Default
  7.     Inherits System.Web.UI.Page
  8.  
  9.     Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
  10.  
  11.         Dim DataSource As String = ""
  12.         Dim Database As String = ""
  13.         Dim Provider As String = "Data Source=" & DataSource & ";Initial Catalog=" & Database & ";Integrated Security=True"
  14.  
  15.         Try
  16.             Dim Con = New SqlConnection(Provider)
  17.             Con.Open()
  18.  
  19.             Dim Cmd = New SqlCommand("SELECT * FROM Employees", Con)
  20.             Dim Reader = Cmd.ExecuteReader()
  21.  
  22.             While (Reader.Read())
  23.                 Response.Write("First Name: " & Reader("FirstName") & " " & "Surname: " & Reader("Surname") & "<br/>")
  24.             End While
  25.  
  26.         Catch ex As Exception
  27.             Response.Write(ex.Message)
  28.         End Try
  29.  
  30.     End Sub
  31. End Class

No comments:

Post a Comment