How do you connect your VB.NET application to SQL Server?Given below
is the sample code which shows how to establish connection between VB.NET
application and SQL Server:
Public sub Form_Load() Dim sampleConnection As New SqlConnection Dim sampleCommand As New SqlCommand Dim sampleReader As SqlDataReader Try sampleConnection.ConnectionString = AppSettings.Item(SampleConnString) sampleConnection.Open() sampleCommand = New SqlCommand(Select rollNo from Students) sampleCommand.Connection = sampleConnection sampleReader = sampleCommand.ExecuteReader() Do While sampleReader.Read() lstRollNo.Items.Add(sampleReader.Item(rollNo)) Loop Catch sampleEx As Exception Throw sampleEx Finally sampleConnection.Close() End Try <appSettings> <add key= SampleConnString value=Server=sampleSQLServer;UserID=scott; Database=Students/> </appSettings> End Sub In this example,
you create a sampleConnection by defining its ConnectionString attribute.
You then open the connection by calling Open() method of sampleConnection.
Now you can use this connection in your command and finally you have to
call close() of the connection.
|