Access database using ADO.NET

zhaozj2021-02-17  53

ADO.NET overview

ADO.NET provides a data source such as Microsoft SQL Server and an unanimous access to the data sources disclosed by OLE DB and XML. Data Sharing User Applications can connect to these data sources using ADO.NET and retrieve, operate, and update data.

ADO.NET effectively decomposes data access to multiple discontinuous components that can be used alone or before the previous use of data operations. The ADO.NET contains a .NET data provider for connecting to the database, execute command, and retrieval results. You can directly process the retrieved results, or put it in an ADO.NET DataSet object to make it together with data from multiple sources or data between the remote processing, and is disclosed in a special manner. ADO.NET DataSet objects can also be used independently of .NET data provider to manage data local data or data from XML.

ADO.NET structure

Previously, data processing mainly depends on the connection-based double-layer model. When the data processing is increasingly using a multi-layer structure, the programmer is converting to the disconnect to provide better scaling for their applications.

ADO.NET borrows XML's power to provide disconnect access to data. The design of the ADO.NET and the design of the XML class in the .NET framework is incorporated - They are all components of the same structure.

The XML class in the ADO.NET and the .NET frame is set in the DataSet object. Regardless of the DataSet is a file or an XML stream, it can use data from the XML source to fill. Regardless of the data source of data in the DataSet, DataSet can be written as XML that conform to the WWW Federation (W3C), and the architecture is included as an XML Architecture Definition Language (XSD) architecture. Due to the DataSet inherent sequence format is XML, it is an excellent medium for moving data between interlayers, which makes DataSet send data and architectures to XML Web Services remotely and the best context from XML Web Services and architectural contexts. select.

The purpose of the design ADO.NET component is to decompose data access from data operations. Complete this task is the two core components of ADO.NET: DataSet and .NET data provider, the latter is a set of components including Connection, Command, DataReader, and DataAdapter objects.

ADO.NET Dataset is the core component of the disconnected structure of ADO.NET. DataSet's design is clear: in order to achieve data access independent of any data source. Therefore, it can be used in a variety of different data sources, for XML data, or for managing applications local data. The DataSet contains a collection of one or more DataTable objects, which consists of data rows and data columns, and primary keys, foreign keys, constraints, and relationship information about data in the DataTable object.

Another core element of the ADO.NET structure is the .NET data provider, the design of its components is quite clear: in order to achieve data operation and fast, enter, read-only access. The Connection object provides connections to the data source. The Command object enables you to access database commands for returning data, modify data, run stored procedures, and send or retrieve parameter information. DataReader provides high-performance data streams from the data source. Finally, DataAdapter provides bridges that connect DataSet objects and data sources. DataAPter executes the SQL command in the data source using the Command object to load the data into the DataSet and make changes to the data from DataSets consistent with the data source.

The .NET data provider can be written for any data source. The .NET framework comes with two .NET data providers: SQL Server .NET data provider and OLE DB .NET data provider.

The following figure illustrates the components of the ADO.NET structure. ADO.NET DATASET

The DataSet object is a core object that supports the disconnect, distributed data scheme of ADO.NET. DataSet is the memory resident representation of the data, regardless of the data source, it will provide a consistent relational programming model. It can be used in a plurality of different data sources for XML data, or data for managing applications locally. DataSet represents the entire data set including related tables, constraints, and intervals.

The following figure shows the DataSet object model.

The method and objects in the DataSet are consistent with the methods and objects in the relational database model.

DataSet can also be kept and reloaded in the form of XML and to maintain and reload its architecture in the form of an XML Architecture Definition Language (XSD) architecture.

Using the general interface provided by ADO.NET, you can write a group that will run when using any .NET data provider.

Special attention to any provider specific syntax used in writing when the code will be used for multiple .NET data providers. For example, the SQL syntax will vary depending on the data source you visit. When it is changed to a different .NET data provider, if the SQL command is isolated as a string constant, the code will make the code easier to maintain.

In addition, it is necessary to keep the order of creating parameters in the code. For the SQL Server .NET data provider, the parameter use name is identified, so the parameter order is not important. However, the OLE DB .NET data provider assigns the parameter value in order to add parameters to the parameter set. Therefore, it is best to always maintain the order of parameters in the code.

Here is the sample code of C #:

[C #]

// you can use each either:

// idbconnection myconn = new sqlConnection ();

// OR:

// idbconnection myconn = new oledbconnection ();

IDBCommand mycommand = myconn.createcommand ();

Mycommand.commandtext = "Select * from customers";

IDataReader myReader = mycommand.executeReader ();

While (MyReader.Read ())

Console.writeline ("{0} / t {1}", myReader.getstring (0), myreader.getstring (1));

Create and use DataSet

ADO.NET Dataset is a memory resident representation of data, regardless of what data is from what data source, it will provide a consistent relational programming model. A DataSet represents the entire dataset, which contains the relationship between the tables,, sorting, and constraints of the data.

There are several ways to use DataSet, which can be applied separately or in combination. you can:

DataTables, DataRelations, and Constraints are created in DataSet and populate them with data.

DataSet is populated with data tables in the relational data source via DataAdapter.

Create a DataSet

An instance of DataSet can be created by calling the DataSet constructor. Please specify an optional name parameter. If the name is not specified for the DataSet, the name is set to "NewDataSet".

You can also create a new DataSet based on existing DataSet. The new DataSet can be: the original copy of the existing DataSet; DataSet's copy, it replicates the relationship structure (ie architecture) but does not contain any data in the existing DataSet; or the subset of Dataset, it contains only the existing DataSet Rows modified using the getChanges method. The following code example demonstrates how to construct a DataSet instance.

[C #]

DataSet Custds = New Dataset ("CustomerRorders");

Add a DataTable to DataSet

ADO.NET allows you to create a DataTable object and add it to an existing DataSet. You can use the PrimaryKey and UNIQUE properties of the Datacolumn object to be added to the DataTable column object to set the DataTable constraint.

The following example constructs a DataSet, add a new DataTable object to the DataSet, and then add three Datacolumn objects to the table. Finally, the code sets a column setting as the primary key column.

[C #]

DataSet Custds = New Dataset ("CustomerRorders");

DataTable ORDERSTABLE = Custds.tables.Add ("Orders");

Datacolumn Pkcol = ORDERSTABLE.COLUMNS.ADD ("ORDERID", TYPEOF (INT32));

ORDERSTABLE.COLUMns.Add ("OrderQuantity", TypeOf (INT32));

ORDERSTABLE.COLUMNS.ADD ("CompanyName", TypeOf (String);

ORDERSTABLE.PRIMARYKEY = New Datacolumn [] {pkcol};

Create and use data sheets

DataSet consists of a collection of tables, relationships, and constraints. In ADO.NET, the DataTable object is used to represent the table in the DataSet. DataTable represents a table of memory within memory; data is local data for its .NET-based applications that are reside, but can be imported from a data source (for example, using the DataAdapter Microsoft® SQL Server).

The DataTable class is a member of the system.data namespace in the ".NET Framework Class". You can create and use DataTable independently, or you can use it as a member of the DataSet, and the DataTable object can also be used with other .NET frameworks (including DataView). You can access a collection of tablets in DataSet through the tables properties of the DataSet object.

The architecture or structure of the table is represented by columns and constraints. Use the DataColumn object and the ForeignKeyConstRAINT and UniqueConstraint object definition DataTable architecture. The columns in the table can be mapped to the columns in the data source, including the values ​​obtained from the expression, and automatically increment their values, or contain the main key value.

In addition to the architecture, DataTable must also have rows, including data and sort data. DataRow class indicates the actual data contained in the table. DATAROW and its properties and methods are used to retrieve, calculate and operate data in the table. The DATAROW object maintains its current status and original state when accessing and changing the data in the row.

You can create a parent child relationship between a table and a table using one or more associated columns in the table. The relationship between the DataTable object can be created using DataRelation. The DataRelelation object can then be used to return a particular row of related sub-lines or fathers. Create a data sheet

DataTable represents a table of memory within memory, can be created and used independently, or by other .NET framework objects, the most common situation is used as a member of DataSet.

DataTable objects can be created by creating using the DataTable constructor, or can be created by passing the constructor parameters to the add method of the tables attribute of the DataSet (it is a DataTableCollection).

DataTable objects can be created in DataAdapter objects or FillSchema methods, or can be created from a predefined or inferred XML architecture using DataSet's READXML, READXMLSCHEMA or Inferxmlschema methods. Note that after adding DataTable as a member of a DataSet's tables collection, it cannot be added to any other DataSet table.

When you first create DataTable, it is no architecture (structure). To define the schema of the table, you must create a Datacolumn object and add it to the table's columns collection. You can also define primary key columns for tables, and you can create a Constraint object and add it to the table's Constraints collection. After defining the architecture for DataTable, the data row can be added to the table by adding the DATAROW object to the ROWS collection.

When you create a DataTable, you don't need to provide a value for the TableName property, you can specify attributes at other times, or keep it empty. However, when adding a table without a TABLENAME value to the DataSet, the table gets an incremental default name Tablen, which begins with "table", starting from Table0.

Note It is recommended that you avoid using the "Table" or "Tablen" when providing a TABLENAME value, because the name you provide may conflict with the existing default table name in DataSet. If the name provided has existed, exceptions will be triggered.

The following example creates an instance of the DataTable object and specifies the name "Customers" for it.

[C #]

DataTable Worktable = New DataTable ("Customers");

The following example creates a DataTable instance, and the method is to add it to the tablet Tables collection.

[C #]

DataSet Custds = New DataSet ();

DataTable CustTable = Custds.tables.Add ("CustTable");

Create and use DataView

DataView enables you to create different views of the data stored in the DataTable, which is usually used for data binding applications. With DataView, you can publish data with different sorting sequences in the table, and you can filter data in line or filter-based expression.

DataView provides data dynamic views, its contents, sorting, and member relationships will reflect changes to the base DataTable in real time. It is different from the DataTable SELECT method, and the latter returns a DataRow array from the table, although its content reflects the changes to the base table, but its member relationships and sort remain static. DataView's dynamic features make it ideal for data binding applications. Similar to the view provided by the database, DataView provides a dynamic view that provides you with a single dataset that can apply different sorting and filtering conditions. However, fairly differences between DataView and database views is that DataView cannot be processed as a table, and the view of the coupling table cannot be provided. In addition, it is not possible to exclude the columns existing in the source table, and it is not possible to add columns that do not exist in the source table (such as compute columns).

You can use DataViewManager to manage view settings of all tables in the DataSet. DataViewManager provides you with a convenient way to manage the default view settings for each table. Binding to DataViewManager is ideal choice when binding a control to a DataSet.

Create DataView

There are two ways to create a DataView. You can use the DataView constructor, you can also create references to the Detatable defaultView property. The DataView constructor can be empty, or DataTable can be used in the form of a single parameter or using DataTable and filtering conditions, sort conditions, and row status filters. More information on additional parameters that can be used with DataView.

Because DataView's index is generated while modifying any sort, rowfilter or rowstatefilter property, the best performance is achieved by providing any initial sorting order or filtering conditions by constructing a function parameter. If you create a DataView without specifying a sort or filter condition, then set the sort, rowfilter or rowstatefilter property, the index is generated at least twice: once when you create DataView, the other is modifying any sort or filtering properties. .

Note that if you do not use the constructor of any parameters to create DataView, DataView will not be used before setting the Table property.

The following code example demonstrates how to use the DataView constructor to create DataView. RowFilter, Sort column, and DataViewRowState will be available with DataTable.

[C #]

DataView Custdv = New DataView (Custds.Tables ["Customers"],

"Country = 'usa'",

"ContactName",

DataViewRowState.currentrows);

The following code demonstrates how to use the defaultview attribute of this table to get a reference to the default DataView for DataTable.

[C #]

DataView Custdv = Custds.tables ["Customers"]. DefaultView;

to sum up

The above is some of the major features of ADO.NET in vs.net, and give you a reference. If you have any suggestions, please Mil I Paulni@citiz.net.

转载请注明原文地址:https://www.9cbs.com/read-28565.html

New Post(0)