Asp. NET Database programming

Source: Internet
Author: User
Tags bind interface connect object model ole
Asp.net| Programming | data | database ASP. NET Ado.net and ADO in ASP, it is an improved version of ADO. In Ado.net, the application programming interfaces (APIs) provided by managed provider make it easy to access data from a variety of data sources, including databases supported by OLE DB and ODBC-supported.

Here are two of the most important concepts in Ado.net: Managed provider and Datasets.

Managed Provider

In the past, data access through ADO employs a two-tier, connectivity-based programming model. As demand for multi-tier applications grows, programmers need a connectionless model. Ado. NET was born. Ado. NET Managed provider is a multilayer structure of connectionless consistent programming model.

Managed Provider provides a link between a dataset and a data center, such as Ms SQL. Managed provider contains a series of interfaces that access the data Center (database). There are three main components:

1, the Connection object connection, command object commands, parameter object parameter provides the interface between data source and dataset. The DataSetCommand interface defines data columns and table mappings, and eventually retrieves a dataset.

2, the data flow provides a high-performance, forward data access mechanism. With IDataReader, you can easily and efficiently access the data stream.

3. The lower-level objects allow you to connect to the database, and then perform specific commands at the database-system levels.

In the past, data processing depended primarily on a two-tier structure and was based on connectivity. The connection is disconnected and the data is no longer accessible. Now, data processing is extended to more than three layers of structure, and, accordingly, programmers need to switch to a connectionless application model. In this way, DataSetCommand plays a very important role in ado.net. It can retrieve a dataset and maintain a "bridge" between a data source and a dataset for data access and modification and preservation. DataSetCommand automatically transforms the various operations of the data into appropriate SQL statements related to the data source. As can be seen from the figure, four command objects: SelectCommand, InsertCommand, UpdateCommand, DeleteCommand, respectively, replace the database query, insert, UPDATE, delete operations.

Managed provider uses local OLE DB to enable data access through COM interop. OLE DB supports automatic and manual transaction processing. Therefore, Managed provider also provides the ability of transaction processing.
DataSet

A dataset is the central concept of ado.net. You can imagine a dataset as a database in memory. It is precisely because of the dataset that programmers can screen the differences between databases in order to obtain a consistent programming model.

Datasets support multiple tables, inter-table relationships, data constraints, and so on. These and relational database models are basically the same.

Accessing the database through Ado.net

Whether from the perspective of grammar, or from the style and design goals, ADO. NET is a significant difference from ADO. In ASP, access to the database through ADO, generally through the following four steps:

1, create a link to the database, that is, ado.connection;

2, query a data set, that is, execute SQL, generate a recordset;

3, the data collection to carry out the required operation;

4, close the data link.

In Ado.net, these steps have changed a lot. Ado. One of the most important concepts of net is dataset. A dataset is a separate collection of data that is not dependent on a database. The so-called independence is: even if the data link is disconnected, or the database is closed, the dataset is still available. If you have used a collection of disconnected records (connectionless Recordset) in an ASP, then the dataset is the most thorough alternative to this technique.
With the dataset, then, ADO. NET access to the database changes accordingly:

1, create a database link;

2. Request a collection of records;

3, the collection of records to the dataset;

4, if necessary, return to step 2nd; (DataSet can hold multiple data sets)

5, close the database link;

6. Do the required operation on the dataset.

The dataset internally uses XML to describe the data. Since XML is a platform-independent, language-independent data Description language, and can describe data for complex data relationships, such as parent-child relationships, datasets can actually accommodate data with complex relationships and no longer rely on database links.

Ado. NET has a lot of objects, we first look at the most basic and most commonly used a few. First look at the adoconnection. Corresponds to the Adodb.connection object of ADO, ADOConnection maintains a link to the database. In order to use the Ado.net object, we need to introduce two NameSpace:System.Data and System.Data.ADO, using the asp.net import directive:

<%@ Import namespace= "System.Data"%>

<%@ Import namespace= "System.Data.ADO"%>

Similar to the Connection object of ADO, the ADOConnection object also has open and close two methods. The following example shows how to connect to the pubs database on a local MS SQL Server.

<%@ Import namespace= "System.Data"%>
<%@ Import namespace= "System.Data.ADO"%>
<%
' Set the connection string ...
Dim strconnstring as String
strconnstring = "Provider=sqloledb; Data source= (local);;" & _
"Initial catalog=pubs; User Id=sa"

' Create Object ADOConnection
Dim objconn as ADOConnection
objconn = New adoconnection

' Set the ADOConnection object's connection string
objconn.connectionstring = strconnstring

objConn.Open () ' Open Data link

' Database operation code omitted

Objconn.close () ' Close data link
objconn = Nothing ' Clears object
%>


The code above is not much different from ADO. It should be mentioned that ADO. NET provides two ways of database connection: ADO method and SQL method. Here we are connected to the database through ADO. For more information on establishing a database connection, we'll talk about it in a later space.

Adodatasetcommand

Another Ado.net object that has to be mentioned is Adodatasetcommand, which is specifically responsible for creating the DataSet object we mentioned earlier. Another important Ado.net object is DataView, which is a view of the dataset. Remember the dataset can hold complex data for a variety of relationships? By DataView, we can limit the dataset's data to a specific range.

The following code shows how to populate the DataSet with Adodatasetcommand:


  

' Create SQL string
Dim strSQL as String = "SELECT * FROM Authors"

' Create object Adodatasetcommand and dataset
Dim Objdscommand as Adodatasetcommand
Dim objdataset As DataSet = New DataSet
Objdscommand = New Adodatasetcommand (strSQL, objconn)

' Populate data to DataSet
' and name the data collection as ' Author information '
Objdscommand.filldataset (Objdataset, "Author information")


Display DataSet

We've got the data ready before. Let's take a look at how to display the data in the dataset. In ASP.net, the commonly used control for displaying a DataSet is a DataGrid, an HTML control in asp.net that can be well represented as a table, with arbitrary control over the appearance of the table and even pagination. Here we just need to use it simply:

<asp:datagrid id= "Datagridname" runat= "Server"/>

The rest of the task is to bind the DataSet to this DataGrid, binding is an important concept of asp.net, we will explain in another text. Generally, you need to bind a DataView to a DataGrid instead of binding the dataset directly. Fortunately, the dataset has a default DataView, and we bind it to the DataGrid:
Myfirstdatagrid.datasource = _
Objdataset.tables ("Author information"). DefaultView
Myfirstdatagrid.databind ()


Usage of the DataSet
The Dataset is not a simple replica of the recordset. In a certain sense, DataView is more like a recordset. If DataReader is the easiest way to access data, the dataset is the most complete data access object. With a dataset, you can manipulate existing data, create a dataset from a program, add a table to a dataset, and build relationships between the table.

Several steps to using a dataset

Step 1th, create a connection to the data source:

SqlConnection con =new SqlConnection ("server=localhost;;uid=sa;;pwd=;;database=pubs");;

The 2nd step is to create a DataSetCommand object, specify the name of a stored procedure or an SQL statement, and specify the data link;

Sqldatasetcommand cmd =new sqldatasetcommand ("SELECT * from Authors", con);

Step 3rd, create a DataSet object

DataSet ds = new DataSet ();;

The 4th step is to call the DataSetCommand Filldata method to populate the dataset with data. Note: The data link is not necessarily open. If the data link is off, the Filldata function opens it and closes the data link after filldata. If the data link is already open, the data link remains open after filldata.

int irowcount = cmd. FillDataSet (ds, "Authors");;

The 5th step is to manipulate the data. Since Filldata returns the number of records, we can construct a loop to manipulate the data in the dataset.


for (int i=0;; i< irowcount;; i++) {
DataRow dr = ds. Tables[0]. Rows[i];;
Console.WriteLine (dr["au_lname"])
}

Data binding Technology

The Repeater, DataList, and DataGrid controls are several related page components in the System.Web.UI.WebControls name Space (Namespace). These controls represent the data that is bound to them through HTML, and they become "list-bound controls" (List-bound controls).

Like other Web Components, these components not only provide a consistent programming model, but also encapsulate the HTML logic associated with the browser version. This feature allows programmers to program on this object model without considering the differences and inconsistencies of various browser versions.

These three controls have the ability to "translate" their related data into various skins. These skins include a table, a multiple-column list, or any HTML stream. At the same time, they also allow you to create arbitrary display effects. In addition, they encapsulate the ability to handle submission data, state management, and event firing. Finally, they provide standard operations at various levels, including selection, editing, paging, sorting, and so on. With these controls, you can easily complete the following Web apps: reports, shopping carts, product listings, query results, navigation menus, and more.


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.