DataSet 类

表示数据在内存中的缓存。

**命名空间:**System.Data
**程序集:**System.Data(在 system.data.dll 中)

语法

声明
<SerializableAttribute> _
Public Class DataSet
    Inherits MarshalByValueComponent
    Implements IListSource, IXmlSerializable, ISupportInitializeNotification, ISupportInitialize, _
    ISerializable
用法
Dim instance As DataSet
[SerializableAttribute] 
public class DataSet : MarshalByValueComponent, IListSource, IXmlSerializable, ISupportInitializeNotification, 
    ISupportInitialize, ISerializable
[SerializableAttribute] 
public ref class DataSet : public MarshalByValueComponent, IListSource, IXmlSerializable, ISupportInitializeNotification, 
    ISupportInitialize, ISerializable
/** @attribute SerializableAttribute() */ 
public class DataSet extends MarshalByValueComponent implements IListSource, IXmlSerializable, 
    ISupportInitializeNotification, ISupportInitialize, ISerializable
SerializableAttribute 
public class DataSet extends MarshalByValueComponent implements IListSource, IXmlSerializable, 
    ISupportInitializeNotification, ISupportInitialize, ISerializable

备注

DataSet 是 ADO.NET 结构的主要组件,它是从数据源中检索到的数据在内存中的缓存。DataSet 由一组 DataTable 对象组成,您可使这些对象与 DataRelation 对象互相关联。您还可通过使用 UniqueConstraintForeignKeyConstraint 对象在 DataSet 中实施数据完整性。有关使用 DataSet 对象的详细信息,请参见 在 ADO.NET 中使用 DataSet

尽管 DataTable 对象中包含数据,但是 DataRelationCollection 允许您遍览表的层次结构。这些表包含在通过 Tables 属性访问的 DataTableCollection 中。当访问 DataTable 对象时,请注意它们是按条件区分大小写的。例如,如果一个 DataTable 被命名为“mydatatable”,另一个被命名为“Mydatatable”,则用于搜索其中一个表的字符串被认为是区分大小写的。但是,如果“mydatatable”存在而“Mydatatable”不存在,则认为该搜索字符串不区分大小写。有关使用 DataTable 对象的更多信息,请参见 创建 DataTable

DataSet 可将数据和架构作为 XML 文档进行读写。数据和架构可通过 HTTP 传输,并在支持 XML 的任何平台上被任何应用程序使用。可使用 WriteXmlSchema 方法将架构保存为 XML 架构,并且可以使用 WriteXml 方法保存架构和数据。若要读取既包含架构也包含数据的 XML 文档,请使用 ReadXml 方法。

在典型的多层实现中,用于创建和刷新 DataSet 并依次更新原始数据的步骤包括:

  1. 通过 DataAdapter 使用数据源中的数据生成和填充 DataSet 中的每个 DataTable

  2. 通过添加、更新或删除 DataRow 对象更改单个 DataTable 对象中的数据。

  3. 调用 GetChanges 方法以创建只反映对数据进行的更改的第二个 DataSet

  4. 调用 DataAdapterUpdate 方法,并将第二个 DataSet 作为参数传递。

  5. 调用 Merge 方法将第二个 DataSet 中的更改合并到第一个中。

  6. 针对 DataSet 调用 AcceptChanges。或者,调用 RejectChanges 以取消更改。

提示

DataSetDataTable 对象从 MarshalByValueComponent 继承而来,并支持用于远程处理的 ISerializable 接口。这些是仅有的可以远程处理的 ADO.NET 对象。

主题 位置
如何:创建类型化数据集 Visual Studio 中的数据访问
演练:在 TreeView 控件中显示分层数据 在 Visual Studio 中构建 ASP .NET Web 应用程序
如何:创建类型化数据集 Visual Studio 中的数据访问
演练:在 TreeView 控件中显示分层数据 在 Visual Studio 中生成 ASP .NET Web 应用程序
演练:在 TreeView 控件中显示分层数据 在 Visual Studio 中生成 ASP .NET Web 应用程序

示例

下面的示例由几种方法组成,这些方法互相结合,从 Northwind 数据库中创建并填充 DataSet

Option Explicit On
Option Strict On

Imports System.Data
Imports system.Data.SqlClient

Public Class NorthwindDataSet

    Public Shared Sub Main()
        Dim connectionString As String = _
            GetConnectionString()
        ConnectToData(connectionString)
    End Sub

    Private Shared Sub ConnectToData( _
        ByVal connectionString As String)

        ' Create a SqlConnection to the Northwind database.
        Using connection As SqlConnection = New SqlConnection( _
           connectionString)

            ' Create a SqlDataAdapter for the Suppliers table.
            Dim suppliersAdapter As SqlDataAdapter = _
               New SqlDataAdapter()

            ' A table mapping names the DataTable.
            suppliersAdapter.TableMappings.Add("Table", "Suppliers")

            ' Open the connection.
            connection.Open()
            Console.WriteLine("The SqlConnection is open.")

            ' Create a SqlCommand to retrieve Suppliers data.
            Dim suppliersCommand As SqlCommand = New SqlCommand( _
               "SELECT SupplierID, CompanyName FROM dbo.Suppliers;", _
               connection)
            suppliersCommand.CommandType = CommandType.Text

            ' Set the SqlDataAdapter's SelectCommand.
            suppliersAdapter.SelectCommand = suppliersCommand

            ' Fill the DataSet.
            Dim dataSet As DataSet = New DataSet("Suppliers")
            suppliersAdapter.Fill(dataSet)

            ' Create a second SqlDataAdapter and SqlCommand to get
            ' the Products table, a child table of Suppliers. 
            Dim productsAdapter As SqlDataAdapter = _
                New SqlDataAdapter()
            productsAdapter.TableMappings.Add("Table", "Products")

            Dim productsCommand As SqlCommand = New SqlCommand( _
               "SELECT ProductID, SupplierID FROM dbo.Products;", _
               connection)
            productsAdapter.SelectCommand = productsCommand

            ' Fill the DataSet.
            productsAdapter.Fill(dataSet)

            ' Close the connection.
            connection.Close()
            Console.WriteLine("The SqlConnection is closed.")

            ' Create a DataRelation to link the two tables
            ' based on the SupplierID.
            Dim parentColumn As DataColumn = _
               dataSet.Tables("Suppliers").Columns("SupplierID")
            Dim childColumn As DataColumn = _
               dataSet.Tables("Products").Columns("SupplierID")
            Dim relation As DataRelation = New _
               System.Data.DataRelation("SuppliersProducts", _
               parentColumn, childColumn)
            dataSet.Relations.Add(relation)

            Console.WriteLine( _
               "The {0} DataRelation has been created.", _
               relation.RelationName)
        End Using

    End Sub

    Private Shared Function GetConnectionString() As String
        ' To avoid storing the connection string in your code,  
        ' you can retrieve it from a configuration file.
        Return "Data Source=(local);Initial Catalog=Northwind;" _
           & "Integrated Security=SSPI;"
    End Function
End Class
using System;
using System.Data;
using System.Data.SqlClient;

namespace Microsoft.AdoNet.DataSetDemo
{
    class NorthwindDataSet
    {
        static void Main()
        {
            string connectionString = GetConnectionString();
            ConnectToData(connectionString);
        }

        private static void ConnectToData(string connectionString)
        {
            //Create a SqlConnection to the Northwind database.
            using (SqlConnection connection =
                       new SqlConnection(connectionString))
            {
                //Create a SqlDataAdapter for the Suppliers table.
                SqlDataAdapter adapter = new SqlDataAdapter();

                // A table mapping names the DataTable.
                adapter.TableMappings.Add("Table", "Suppliers");

                // Open the connection.
                connection.Open();
                Console.WriteLine("The SqlConnection is open.");

                // Create a SqlCommand to retrieve Suppliers data.
                SqlCommand command = new SqlCommand(
                    "SELECT SupplierID, CompanyName FROM dbo.Suppliers;",
                    connection);
                command.CommandType = CommandType.Text;

                // Set the SqlDataAdapter's SelectCommand.
                adapter.SelectCommand = command;

                // Fill the DataSet.
                DataSet dataSet = new DataSet("Suppliers");
                adapter.Fill(dataSet);

                // Create a second Adapter and Command to get
                // the Products table, a child table of Suppliers. 
                SqlDataAdapter productsAdapter = new SqlDataAdapter();
                productsAdapter.TableMappings.Add("Table", "Products");

                SqlCommand productsCommand = new SqlCommand(
                    "SELECT ProductID, SupplierID FROM dbo.Products;",
                    connection);
                productsAdapter.SelectCommand = productsCommand;

                // Fill the DataSet.
                productsAdapter.Fill(dataSet);

                // Close the connection.
                connection.Close();
                Console.WriteLine("The SqlConnection is closed.");

                // Create a DataRelation to link the two tables
                // based on the SupplierID.
                DataColumn parentColumn =
                    dataSet.Tables["Suppliers"].Columns["SupplierID"];
                DataColumn childColumn =
                    dataSet.Tables["Products"].Columns["SupplierID"];
                DataRelation relation =
                    new System.Data.DataRelation("SuppliersProducts",
                    parentColumn, childColumn);
                dataSet.Relations.Add(relation);
                Console.WriteLine(
                    "The {0} DataRelation has been created.",
                    relation.RelationName);
            }
        }

        static private string GetConnectionString()
        {
            // To avoid storing the connection string in your code, 
            // you can retrieve it from a configuration file.
            return "Data Source=(local);Initial Catalog=Northwind;"
                + "Integrated Security=SSPI";
        }
    }
}

继承层次结构

System.Object
   System.ComponentModel.MarshalByValueComponent
    System.Data.DataSet

线程安全

该类型对于多线程读操作是安全的。您必须使任何写操作同步。

平台

Windows 98、Windows 2000 SP4、Windows CE、Windows Millennium Edition、Windows Mobile for Pocket PC、Windows Mobile for Smartphone、Windows Server 2003、Windows XP Media Center Edition、Windows XP Professional x64 Edition、Windows XP SP2、Windows XP Starter Edition

.NET Framework 并不是对每个平台的所有版本都提供支持。有关受支持版本的列表,请参见系统要求

版本信息

.NET Framework

受以下版本支持:2.0、1.1、1.0

.NET Compact Framework

受以下版本支持:2.0、1.0

请参见

参考

DataSet 成员
System.Data 命名空间

其他资源

在 ADO.NET 中使用 DataSet