Friday, July 2, 2010

Connect to Database in VB.NET

This post shows how to connect to database and execute select query in VB.NET.

Please follow the below steps

1. If the database name is : NorthWindDB.

2. in web.config file add the following code.

3. In the code file, import the following namespaces.

Imports System.Data;
Imports System,Data.SqlClient;

4. Add the reference to System.Configuration namespace. By right clicking the project -> click Add Reference -> select System.Configuration -> ok.

Write the following code to connect to the database and execute the query "select * from Emp". This query retreives all the rows from the Emp table of the NorthWindDB database.

5.Dim con as New SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings("NorthWindDB").ConnectionString()

dim cmd as New SqlCommand(con,"select * from Emp")

dim dr as SqlDataReader = cmd.ExecuteReader()


//Process the data as per your requirement.

End While

No comments:

Post a Comment