.NET开发

本类阅读TOP10

·vs.net 2005中文版下载地址收藏
·NHibernate快速指南(翻译)
·【小技巧】一个判断session是否过期的小技巧
·通过Web Services上传和下载文件
·?dos下编译.net程序找不到csc.exe文件
·VB/ASP 调用 SQL Server 的存储过程
·学习笔记(补)《.NET框架程序设计(修订版)》--目录
·对比.NET PetShop和Duwamish来探讨Ado.NET的数据库编程模式
·Autodesk官方最新的.NET教程(一)(vb.net版)
·Duwamish深入剖析-结构篇

分类导航
VC语言Delphi
VB语言ASP
PerlJava
Script数据库
其他语言游戏开发
文件格式网站制作
软件工程.NET开发
Introduction to DataSets and working with XML files

作者:未知 来源:月光软件站 加入时间:2005-2-28 月光软件站

Introduction to DataSets and working with XML files

By Alexandru Savescu

数据集与XML文件的使用介绍

This article gives you an introduction to .NET's DataSets and how you can use them with XML files 

这篇文章介绍了.NET数据集并教会你如何把它们跟XML文件结合起来使用

Introduction

介绍

This article gives you an introduction to using DataSets and how to use them with XML files. Working with them really makes your life easier when you want to share data from a data source and you are thinking of XML.

这篇文章介绍了.NET数据集并教会你如何把它们跟XML文件结合起来使用。当你想从数据源中共享数据而且想到使用XML的话,这将是很轻松的事情。

System Requirements

系统要求

To compile the solution you need to have Microsoft Visual Studio .NET installed. To run any of the client executable you need to have the .NET framework installed.

为了编译程序,你必须安装微软Visual Studio .NET。同时为了客户端程序的执行,.NET框架也是不可缺少的。

The sample provided is a simple application written in C#. It displays a form with a DataGrid. By default, the application connects to a SQL Server, binds the Northwind database and fetches some parent records from table Customers and some child records from table Orders. By default, the application assumes that you have an instance of SQL Server installed on your machine. If this is not the case, then you must manually modify the connection string and then rebuild the sample.

这里提供的是一个用C#编写的小程序。它用了一个DataGrid来显示数据内容。默认情况下,程序链接到SQL Server服务器,帮定Northwind数据库,从Customers表取出主表数据,从Orders表取从表数据。这里假定你已经安装了SQL Server数据库服务器。如果不这样的话,你必须手动修改连接字符串并重新建立。

Then, you can save the dataset to XML file. Schema information is also saved.

然后你就可以把数据集保存到XML文件了,架构信息也会被保存的。

What is a DataSet?

什么是数据集?

A DataSet object is a very generic object that can store cached data from a database in a very efficient way. It is member of the System::Data namespace.

一个数据集对象是一个能够以高效方来存储来自数据库高速缓冲数据的通用对象。它是System::Data命名空间的一个成员。

One obvious question is: When to use a dataset? Well, the answer is: it depends. You should consider that a dataset is a collection of in-memory cached data. So it's good to use datasets when:

一个明显的问题是:什么时候使用数据集呢?答案是这样的:它取决于。你应该明白数据集存储的是内存缓冲器里的数据。所以这几个情况下使用数据集是最好的:

  • You are working with multiple separated tables or tables from different data sources.
  • You are exchanging data with another application such as a Web Service.
  • You perform extensive processing with the records in the database. If you use a SQL query every time you need to change something, processing each record may result in connection being held open which may affect performance.
  • You want to perform XML/XSLT operations on the data.

l         你同时使用多个独立的数据表或数据表来自不同的数据源。

l         你要作类似于Web Service这样的数据交换。

l         你要处理数据库重大量的记录。如果你每次都使用一条SQL查询来操作数据库,这样将影响性能。

l         你想使用XML/XSLT对数据进行操作。

You should not use a dataset if:

如果在这种情况下,你就应该使用数据集:

  • You are using Web Forms in your application because Web Forms and their controls are recreated each time a page is requested by the client. Thus, creating, filling and destroying a dataset each time will be inefficient unless you plan to cache it between roundtrips.

你在程序使用Web窗体,而Web窗体和它们的控件每次在页面生成的时候都会在客户端重新建立。这样,你要是不打算把数据集放在缓冲里,每次建立、填充和销毁数据集都会影响效率。

A DataSet has a DataTableCollection object as a member that is nothing but a collection of DataTable objects. You declare a DataSet object and add tables to it like this (in Managed C++):

数据集有存放数据表集合的DataTableCollection对象。你可以声明一个数据集对象并像下面这样把表添加进去。

  // Declare the DataSet object

  DataSet* MyDataSet = new DataSet ("MyDataSet"); // give it a name here

 

  // Add two tables to it

  // - add a Table named Table1

  DataTable* Table1 = MyDataSet->Tables->Add ("Table1");

 

  // - add a Table named Table2

  DataTable* Table2 = MyDataSet->Tables->Add ("Table2");

You can refer the tables later either using the pointers returned by the Add method or like this:

也可以用Add方法或这样返回的结果来引用数据表:

  DataTable* table = MyDataSet->Tables->Item[0]; // or

  DataTable* table = MyDataSet->Tables->Item["Table1"];

                                                  // isn't this indexation cool?

A DataTable object has two important members: Rows and Columns. Rows is a DataRowCollection object and Columns is a DataColumnCollection. DataRowCollection is a collection of DataRow objects and DataColumnCollection is a collection of DataColumn objects. I am sure you can easily figure out what these objects represent. :)

数据表对象有两个重要成员:行和列(Rows/Columns)。Rows是一个DataRowCollection对象,而Columns是一个DataColumnColletion对象。DataRowCollectionDataColunmCollection分别是DataRowDataColumn对象集合。相信你能够轻松的理解这些对象的含义。J

Adding data to a data set is straight-forward:

单向填充数据

  // adding data to the first table in the DataSet

  DataTable* Table1 = MyDataSet->Tables->Item[0];

 

  // add two columns to the table

  Table1->Columns->Add ("Column1");

  Table2->Columns->Add ("Column2");

 

  // get the collection of rows

  DataRowCollection* drc = Table1->Rows;

 

  // create a vector of Objects that we will insert in current row

  Object* obj[] = new Object* [2];

 

  obj[0] = new String ("Item 1");

  obj[1] = new String ("Item 2");

 

  // add them to the dataset

  drc->Add (obj);

If you want to specify the data type of a particular column you should use the DataColumn::DataType property. You can set any of the following data types: Boolean, Byte, Char, DateTime, Decimal, Double, Int16, Int32, Int64, SByte, Single, String, TimeSpan, UInt16, UInt32, UInt64.

如果你想指定某列的数据类型,可以使用DataColumn::DataType。你也可以设置下面这些数据类型:BooleanByteCharDataTimeDecimalDoubleInt16Int32Int64SByteSingleStringTimeSpanUInt16UInt32UInt64

That's it! Well, that's all you have to do if you want to build up your data set manually. This is not how it is done if you want to connect to a real data source.

就这些内容了,如果你想手动建立数据集,这就是你需要知道的。如果你要连到一个真正的数据源的话,就不是这样了。

Binding a Database

帮定一个数据库

To connect to a database server (such as SQL Server) and fill a dataset from there you need three additonal objects: a Connection, a DataCommand and a DataAdapter object.

要连接到数据库服务器(例如SQL Server)并要填充数据集,你需要三个额外的对象:ConnectionDataCommandDataAdapter

The Connection object is used to connect to the database object. You must provide a connection string to it. Also, if your application is using transactions, you must attach a transaction object to the connection.

Connection用于连接数据库对象。你必须为它提供一个连接字符串。如果你的程序使用事务的话,你也得把事务对象附加给连接。

The DataCommand object is used to sending commands to the database server. It includes four System::String objects named SelectCommand, InsertCommand, UpdateCommand and DeleteCommand. I believe it is obvious what these string objects represent, nothing else but the four basic SQL operations.

DataCommand对象用于给数据库服务器发送命令。它包含四个System::String类型的对象:SelectCommandInsertCommandUpdateCommandDeleteCommand。它们的含义很明显,就是四个基本的SQL操作。

The DataAdapter object is the object that does all the magic work. It fills the DataSet with data from the database and updates data from the DataSet to the database.

DataAdapter对象很奇特。它能从数据库取出数据并填充数据集,还可以把数据集更新的内容反填到数据库。

You may now wonder what are the classes that correspond to the objects described above. Well, Microsoft have prepared two sets of classes - you can't say life is getting much easier in .NET can you? :). The first set is based on OLE DB and is part of the System::Data::OleDb namespace. It contains the following classes: OleDbConnection, OleDbCommand and OleDbDataAdapter. The other set of classes is optimized for working with Microsoft SQL Server. It is part of the System::Data::SqlClient namespace and its classes include: SqlConnection, SqlCommand and SqlDataAdapter.

你现在可能想知道对应上述描述的类是什么了吧?微软给我们准备了两组类——你不得不说.NET时代的生活都是那么的容易,不是吗?J 第一组是基于OLE DB的,同时也是System::Data::OleDb命名空间的一部分。它包含下面几个类:OleDbConnectionOleDbCommandOleDbDataAdapter。另外一组是为微软SQL Server优化的类。它是System::Data::SqlClient命名空间的一部分,它的类包含:SqlConnectionSqlCommandSqlDataAdapter

Here is a complete example of how to connect to the database and fill the dataset. I have used the classes optimized for SQL Server. If you need to use OLE DB you only have to replace "Sql" with "OleDb". We try to fetch two tables Table1 and Table2 and set a parent-child relationship between them.

这里给出了如何连接数据库并填充数据集的完全代码。我使用了为SQL Server优化的类。如果你想使用OLE DB的话,只要把“Sql”替换成“OleDb”就可以了。我们试着取出Table1Table2两个表并在它们之间建立一个主从关系。

  // Create a database connection string

  String* str = new String ("user id=sa;password=;initial catalog=MyDB;"

                            "data source=(local)");

 

  // Create the database connection object

  SqlConnection* sqlcon = new SqlConnection (str);

 

  sqlcon->Open (); // open it

 

  // create the first SQL query

  String* strTable1 = String::Format ("SELECT * FROM Table1 "

    "WHERE Field1 = {0}", FieldID.ToString ());    // FieldID is

                   // an interger used to filter our query.

 

  // create the second SQL query. It joins the first table to select only those

  // fields in relation

  String* strTable2 = String::Format ("SELECT T2.* FROM Table2 T2 "

                   "INNER JOIN Table1 T1 ON T2.ParendID = T1.ID "

                   "WHERE T1.Field1 = {0}", Field1.ToString ());    // FieldID is

                   // an interger used to filter our query.

 

  // create the SQL command objects. We pass in the contructor the

  // SqlConnection object and the query string

  SqlCommand* sqlTable1 = new SqlCommand (strTable1, sqlcon);

  SqlCommand* sqlTable2 = new SqlCommand (strTable2, sqlcon);

 

  // Create a data adapter for every table. We pass the SqlComand objects as parameters

  SqlDataAdapter* Table1Adapter = new SqlDataAdapter (sqlTable1);

  SqlDataAdapter* Table2Adapter = new SqlDataAdapter (sqlTable2);

 

 

  // now we create the dataset object and we give it a name

  DataSet* MyDataSet = new DataSet ("MyDataSet");

 

  // we inform the dataset object about the tables it is going to contain

  // by adding those tables to the dataset.

 

  DataTable* Table1 = BackupDataSet->Tables->Add ("Table1");

  DataTable* Table2 = BackupDataSet->Tables->Add ("Table2");

 

  // now we are filling the Dataset using the Dataadapter objects

  // We need not say anything to the DataSet object about the

  // columns of the table and their data type. The DataAdapter objects

  // takes care of everything.

 

  Table1Adapter->Fill (Table1);

  Table2Adapter->Fill (Table2);

 

  // To ensure relationships between Tables we must add a DataRelation object

  // We assume that between column 0 in Table1 and column 1 in Table2 there is

  // a one-to-many relationship

 

  MyDataSet->Relations->Add (Table1->Columns->Item[0],

                             Table2->Columns->Item[1]);

For details about relations and constraints you should read about the Constraint class and the two classes derived from it, ForeignKeyConstraint and UniqueConstraint.

关于关系和约束你可以参考Constraint类和从它继承而来的ForeignKeyConstraintUniqueConstraint类。

Working with XML files

使用XML文件

DataSets can work with XML files very easily. There are two methods to serialize a DataSet object. These are DataSet::WriteXml and DataSet::WriteXmlSchema. The first one writes data to the XML file and may include also schema information. It is useful when you want to write an XML file that has schema information embedded. However, if you prefer schema information in a separate (.xsd) file you should use the DataSet::WriteXmlSchema method.

数据集跟XML很容易工作。有两个方法??????数据集对象。DataSet::WriteXmlDataSet::WriteXmlSchema。第一个是往XML文件里写数据,也可以包含架构信息。但是,如果想把架构信息存储在一个独立的文件(.xsd)中,你可以使用DataSet::WriteXmlSchema方法。

There are also plenty of classes in the System::Xml namespace: XmlWriter, XmlReader, XmlTextWriter, XmlDataDocument to name a few. You can use those with a dataset to perform some advanced XML operations. For instance, if you want to write a dataset to an XML file you can either use

System::Xml命名空间有许多类:XmlWriterXmlReaderXmlTextWriterXmlDataDocument等。你可以用这些配合数据集执行一些高级XML操作。例如,如果你想把数据集写入XML文件,也可以这样用

  // recevies a DataSet in constructor

  XmlDataDocument* xmlDoc = new XmlDataDocument(MyDataSet);

  XmlTextWriter* Output = new XmlTextWriter ("C:\\Myfile.xml", NULL);

 

  // perform some formatting

  Output->Formatting = Formatting::Indented;

  Output->Indentation = 2;

 

  // and write it

  <