Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

ASP.NET Database Connection

ASP.NET Web Forms - Database Connection


ADO.NET is also a part of the .NET Framework. ADO.NET is used to handle data access. Through ADO.NET, you can manipulate databases.


Try it - Example

Database Connection - Binding to the DataList Control

Database Connection - Binding to the Repeater Control


What is ADO.NET?


Creating a Database Connection

In our example, we will use the Northwind database.

First, import the "System.Data.OleDb" namespace. We need this namespace to work with Microsoft Access and other OLE DB database providers. We will create the database connection in the Page_Load subroutine. We create a dbconn variable and assign it a new OleDbConnection class with a connection string that indicates the OLE DB provider and the database location. Then we open the database connection:

<%@ Import Namespace="System.Data.OleDb" %>

**Note:** This connection string must be a single continuous string with no line breaks!


Creating a Database Command

To specify the records to be retrieved from the database, we will create a dbcomm variable and assign it a new OleDbCommand class. This OleDbCommand class is used to issue SQL queries against the database tables:

<%@ Import Namespace="System.Data.OleDb" %>


Creating a DataReader

The OleDbDataReader class is used to read a stream of records from the data source. The DataReader is created by calling the ExecuteReader method of the OleDbCommand object:

<%@ Import Namespace="System.Data.OleDb" %>


Binding to the Repeater Control

Then, we bind the DataReader to the Repeater control:

Example

<%@ Import Namespace="System.Data.OleDb" %>

Companyname Contactname Address City
<%#Container.DataItem("companyname")%> <%#Container.DataItem("contactname")%> <%#Container.DataItem("address")%> <%#Container.DataItem("city")%>

Demo Example »


Closing the Database Connection

If you no longer need to access the database, remember to close the DataReader and the database connection:

dbread.Close()

dbconn.Close()