Analysis. The new mechanism of XML data access under Net

Source: Internet
Author: User
Tags new features web services client
xml| Access | data one. Objective:

The importance of XML as a cornerstone of Web services is self-evident, and it is increasingly being valued by developers. At the same time, with the introduction of various new development tools, the access mechanism of XML data has become more and more flexible and diverse. NET Framework provides several new XML data access mechanisms for developers, each of which provides different XML data access support. So it's important for developers to choose the right and proper XML data access mechanism, which can affect the complexity of project development and the overall efficiency of the application.

Generally speaking,. NET Framework provides developers with two new mechanisms of data access mechanism and SqlDataReader XML data access mechanism in Ado.net. For convenience, we might refer to the former mechanism as the ado.net mechanism, and then the SqlDataReader mechanism. This article I will mainly introduce these two mechanisms, and I will introduce SQLXML and ADO 2.6, the two more traditional XML data access mechanism, and at the end of their performance to make a comparison, so that readers more clearly in the specific application should choose which mechanism. The example program in this article will use the Northwind database in SQL Server, and by accessing the database we can obtain the corresponding XML data and compare and analyze the different access mechanisms accordingly.

Two Introduction to various mechanisms:

Ado. NET is an ADO upgrade version, it provides us with a new data access mechanism, while improving the efficiency of data access while it also greatly simplifies the workload of developers, so the mastery and use of ado.net for development is the essential ability of. NET developers.

Ado. NET provides developers with two types of data access modes: one for connection mode (Connected) and one for connectionless mode (disconnected). The previous pattern is the same as the traditional ADO pattern, and the latter pattern is. NET is also recommended by. NET, and the core of this pattern is the DataSet object (DataSet) in Ado.net. The class of the DataSet object is in the System.Data namespace, and it has fairly good support for XML. When working in disconnected mode, DataSet objects can store data in main memory in XML and provide user action, so it is possible to translate relational data into hierarchical, well-formed XML data using a simple method, which is the ado.net mechanism mentioned earlier.

Next, I will introduce the specific method of XML data access under this mechanism by setting up an instance program. First, create a new C # project for a console application that mainly shows the efficiency of different XML data access mechanisms. Adding a new class, the filename may be named DBXml.cs, which contains several different implementations of the XML data access mechanisms, namely: Executeadonetselect, Executesqldatareaderselect and Executesqlxmlselect, respectively, represent the ado.net mechanism, the SqlDataReader mechanism, and the SQLXML mechanism, and the ADO 2.6 mechanism is described later. Next, add the necessary namespaces to the class.

Using System;
Using System.Data;
Using System.Data.SqlClient;
Using System.Text;
Using System.Xml;
Using Microsoft.Data.SqlXml;



Where you need to add a reference to the MICROSOFT.DATA.SQLXML component for the Microsoft.Data.SqlXml namespace, which is available after you install SQLXML 3.0, as shown in Figure 1:




Figure 1


Now add the Executeadonetselect () method to the class, which performs a select query operation on the database, which is implemented as follows:

public string Executeadonetselect (string CustomerID,
String ConnectionString)
{
Create a database Connection object
SqlConnection myconnection = new SqlConnection (ConnectionString);
Create a data adapter object
SqlDataAdapter mySqlDataAdapter1 = new SqlDataAdapter ("SELECT *
From customers WHERE CustomerID = @CustomerID ", myconnection);
Add parameters to its parameter set
MYSQLDATAADAPTER1.SELECTCOMMAND.PARAMETERS.ADD ("@CustomerID",
SqlDbType.Char, 5, "CustomerID");
mysqldataadapter1.selectcommand.parameters["@CustomerID"].
Value = CustomerID;
Create a DataSet object
DataSet myDataSet = new DataSet ();
Populating DataSet objects with the Fill method of the DataSet object
Mysqldataadapter1.fill (myDataSet, "Customers");
To close a database connection
Myconnection.close ();
Returns the XML form of data in a DataSet object
return Mydataset.getxml ();
}



The above Executeadonetselect () method first creates a SqlConnection object based on the incoming database connection string, and then creates a SqlDataAdapter object. and passes a SELECT statement and the SqlConnection object above to its constructor. The SELECT statement contains a user ID parameter, so you must add the parameter to the SelectCommand parameter set of the SqlDataAdapter object and assign a value to the parameter. The next two steps create a new DataSet object and populate the DataSet object with the SqlDataAdapter object above, which, although simple, accomplishes most of the work. Finally, the database connection is closed and the data in the DataSet object is returned as XML.

Next, add the Executesqldatareaderselect () method to the class, which is as follows:

public string Executesqldatareaderselect (string CustomerID,
String ConnectionString)
{
SqlDataReader mydatareader = null;
Create a database Connection object
SqlConnection mysqlconnection = new SqlConnection
(ConnectionString);
Create a database command object and use the FOR XML clause in the SQL statement
SqlCommand Mysqlcommand = new SqlCommand ("SELECT * from Customers
WHERE CustomerID = @CustomerID for XML RAW ", mysqlconnection);
Mysqlcommand.commandtype = CommandType.Text;
Add parameters to its parameter set
MYSQLCOMMAND.PARAMETERS.ADD ("@CustomerID", SqlDbType.Char, 5,
"CustomerID");
mysqlcommand.parameters["@CustomerID"]. Value = CustomerID;
Mysqlconnection.open ();
Performs a executereader operation on a database command object to obtain a data reader object
MyDataReader = Mysqlcommand.executereader (CommandBehavior.
CloseConnection);
Create an StringBuilder object to construct an XML string
StringBuilder XML = new StringBuilder (8192);
Constantly get XML data from the data reader and add it to the StringBuilder object
while (Mydatareader.read ())
{
if (!mydatareader.isdbnull (0))
Xml. Append (mydatareader.getstring (0));
}
Mydatareader.close ();
Mysqlconnection.close ();
Returns the string form of the XML data
return XML. ToString ();
}



The SqlDataReader class provides us with a read-only, forward-only way of accessing data, which makes it one of the fastest ways to access a SQL Server database. However, SqlDataReader classes do not directly support XML-type data, you must manually write code to convert the data to XML data or to return XML-type data by running a FOR XML query clause. Here, we will use the FOR XML RAW clause to get the XML data.

The above Executesqldatareaderselect () method first declares a SqlDataReader object and then creates a SqlConnection object from the database connection string parameter of the function, and according to the XML The SELECT statement of the RAW clause and the SqlConnection object above create a SqlCommand object. The method then adds a parameter to the SqlCommand parameter set and assigns a value to the user ID parameter. When the SqlConnection connection is opened, the method assigns the return value of the SqlCommand object's ExecuteReader () method to the SqlDataReader object. and reads the XML data from the SqlDataReader object through a StringBuilder object. Finally, the method closes the SqlDataReader object and the SqlConnection object and returns the XML data as a string.

Finally, add the Executesqlxmlselect () method to the class, which is as follows:

public string Executesqlxmlselect (string CustomerID, String
ConnectionString, BOOL clientside)
{
Create a SqlXmlCommand object
SqlXmlCommand cmd = new SqlXmlCommand (ConnectionString);
Cmd. Roottag = "Customers";
Cmd. Clientsidexml = clientside;
Cmd.commandtext = "SELECT * from Customers WHERE CustomerID =
' + CustomerID + ' for XML RAW ';
Performs the executexmlreader operation of the SqlXmlCommand object to obtain a XmlReader object
XmlReader xr = cmd. ExecuteXmlReader ();
Create a XmlDocument object
XmlDocument xd = new XmlDocument ();
Loads the obtained XML data into a DOM using its Load method and returns the string form of the XML data
Xd. Load (XR);
return XD. OuterXml
}



The SQLXML managed class is part of the SQLXML 3.0 package, and the SQLXML 3.0 package extends the XML functionality of SQL Server 2000. The SQLXML managed class is a native. NET class that provides the ability to programmatically access XML data. The Executesqlxmlselect () method above first creates a SqlXmlCommand object using the database connection string. At the same time, XML data obtained by the FOR XML clause is often just an XML fragment, not well-formed (well-formed) XML data, and to make XML well-formed, you must set the Roottag attribute of the SqlXmlCommand object. In this example, we set this property to "Customers".

Previous versions of the SQLXML package generate XML data on the server side and then pass it on to the client. In this way, because the XML data stream returned by the server side is much larger than the original binary format data stream, a scalability problem arises. The 3.0 version of the SQLXML package allows the server to pass data in binary format to the client, and then further converts the data into XML format on the client, which solves the scalability problems that existed in the original version. The way to implement this feature in the 3.0 SQLXML package is simple, as long as you set the Clientsidexml property of the SqlXmlCommand object to True. This way, the program continues to use a SELECT statement with a FOR XML clause, but the managed class strips the FOR XML clause before sending the SQL statement to SQL Server. The database will not find the FOR XML clause, so the data returned from the server to the client is in binary format. After the client gets the data returned from the server, the managed class will then convert the data to XML format.

In the above program, we get a XmlReader object by executing the ExecuteXmlReader () method of the SqlXmlCommand object, and use it to populate a XmlDocument object. Finally, the OuterXml property of the XmlDocument object is returned to the caller.

Above, I introduced to you the ado.net mechanism, SqlDataReader mechanism and SQLXML mechanism of these three different methods, the following is the use of these three different methods of a result map, from the results of the graph readers can see that the method is the most efficient.




Figure 2


Finally, we want to introduce the ADO 2.6 mechanism, which is implemented in VB 6.0. Let's first create an ActiveX DLL project named DBXMLVS6, and then modify Class1 to ADO26, then add a reference to ActiveX Data Objects 2.6. Once finished, add a ExecuteSelect () method to the class as follows:

Public Function ExecuteSelect (
CustomerID as String,
ConnectionString as String)
As String
Set conn = New ADODB. Connection
Conn. ConnectionString = ConnectionString
Conn. Open

Set cmd = New adodb.command
Cmd. ActiveConnection = conn
Cmd.commandtext = "SELECT * FROM Customers
where CustomerID = ' "& CustomerID &" "
Set rs = cmd. Execute

Set Adostream = New ADODB. Stream
Adostream.type = adTypeText
Adostream.open
Rs. Save Adostream, adPersistXML

' Returns an XML string
ExecuteSelect = Adostream.readtext ()
End Function



As with other instances, the above program creates and opens a database connection. It then creates a command object and sets its ActiveConnection property to the Connection object above, and the SELECT statement used in the program is the same as in the previous instance. The program then passes the return value of the Execute () method of the Command object to a Recordset object. The program then creates an ADO Stream object and sets its Type property to adTypeText to open it at the same time. Once the stream object is opened, invoking the Save () method of the Recordset object saves the data in XML format. Finally, the program returns the XML data to the caller through the READTEXT () method of the Stream object.

In combination with the four different XML data access mechanisms described above, I have tested the performance and scalability of XML data access using ASP and ASP.net pages to invoke components, and the results of the performance analysis shown in the following figure are given to readers for reference.




Figure 3


Three Summarize:

This article I introduced to you. NET Framework, XML data access continues to evolve as Microsoft continues to add new features and improve performance, with four different mechanisms for XML data access. At the same time, given that the new version of the SQL Server database server adds a lot of native support for XML, we can expect that XML data access will be greatly developed in the near future.



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.