DataSet.Load DataSet.Load DataSet.Load Method

定义

通过所提供的 IDataReader,用某个数据源的值填充 DataSetFills a DataSet with values from a data source using the supplied IDataReader.

重载

Load(IDataReader, LoadOption, DataTable[]) Load(IDataReader, LoadOption, DataTable[]) Load(IDataReader, LoadOption, DataTable[])

使用提供的 DataSet 以数据源的值填充 IDataReader,同时使用 DataTable 实例的数组提供架构和命名空间信息。Fills a DataSet with values from a data source using the supplied IDataReader, using an array of DataTable instances to supply the schema and namespace information.

Load(IDataReader, LoadOption, String[]) Load(IDataReader, LoadOption, String[]) Load(IDataReader, LoadOption, String[])

使用所提供的 DataSet,并使用字符串数组为 DataSet 中的表提供名称,从而用来自数据源的值填充 IDataReaderFills a DataSet with values from a data source using the supplied IDataReader, using an array of strings to supply the names for the tables within the DataSet.

Load(IDataReader, LoadOption, FillErrorEventHandler, DataTable[]) Load(IDataReader, LoadOption, FillErrorEventHandler, DataTable[]) Load(IDataReader, LoadOption, FillErrorEventHandler, DataTable[])

使用提供的 DataSet 以数据源的值填充 IDataReader,同时使用 DataTable 实例的数组提供架构和命名空间信息。Fills a DataSet with values from a data source using the supplied IDataReader, using an array of DataTable instances to supply the schema and namespace information.

注解

方法提供了一种方法,用于填充DataTableIDataReader实例中检索到的单个数据。 LoadThe Load method provides a technique for filling a single DataTable with data, retrieved from an IDataReader instance. 此方法提供了相同的功能,但允许你将中的多个结果IDataReader集加载到DataSet中的多个表中。This method provides the same functionality, but allows you to load multiple result sets from an IDataReader into multiple tables within a DataSet.

如果 DataSet 已经包含行,则从数据源传入的数据与现有行合并。If the DataSet already contains rows, the incoming data from the data source is merged with the existing rows.

Load方法可用于几个常见方案,所有这些方案都围绕从指定数据源获取数据并将其添加到当前数据容器(在本例中为DataSet)而居中。The Load method can be used in several common scenarios, all centered around getting data from a specified data source and adding it to the current data container (in this case, a DataSet). 这些方案描述了的标准用法DataSet,描述了其更新和合并行为。These scenarios describe standard usage for a DataSet, describing its update and merge behavior.

与单个主数据源同步或更新。DataSetA DataSet synchronizes or updates with a single primary data source. DataSet跟踪更改,允许与主数据源同步。The DataSet tracks changes, allowing synchronization with the primary data source. 此外,可以接受DataSet来自一个或多个辅助数据源的增量数据。In addition, a DataSet can accept incremental data from one or more secondary data sources. DataSet不负责跟踪更改以便与辅助数据源同步。The DataSet isn't responsible for tracking changes in order to allow synchronization with the secondary data source.

假设有这两个假设数据源,用户可能需要以下行为之一:Given these two hypothetical data sources, a user is likely to require one of the following behaviors:

  • DataSet主数据源初始化。Initialize DataSet from a primary data source. 在这种情况下,用户想要使用主DataSet数据源中的值初始化一个空的。In this scenario, the user wants to initialize an empty DataSet with values from the primary data source. 修改一个或多个 DataTable 的内容。One or more DataTable's contents are modified. 稍后,用户打算将更改传播回主数据源。Later the user intends to propagate changes back to the primary data source.

  • 保留更改并从主数据源重新同步。Preserve changes and re-synchronize from the primary data source. 在这种情况下,用户希望采用前面DataSet方案中填充的内容并执行与主数据源的增量同步,同时保留在中所做DataSet的修改。In this scenario, the user wants to take the DataSet filled in the previous scenario and perform an incremental synchronization with the primary data source, preserving modifications made in the DataSet.

  • 来自辅助数据源的增量数据馈送。Incremental data feed from secondary data sources. 在这种情况下,用户想要合并一个或多个辅助数据源的更改,并将这些更改传播回主数据源。In this scenario, the user wants to merge changes from one or more secondary data sources, and propagate those changes back to the primary data source.

Load方法可以实现所有这些方案。The Load method makes all these scenarios possible. 此方法允许您指定加载选项参数,以指示与要加载的行DataTable合并在一起的行的方式。This method allows you to specify a load option parameter, indicating how rows already in a DataTable combine with rows being loaded. 下表描述了LoadOption枚举提供的三个加载选项。The following table describes the three load options provided by the LoadOption enumeration. 在每种情况下,说明指示传入数据中行的主键与现有行的主键匹配时的行为。In each case, the description indicates the behavior when the primary key of a row in the incoming data matches the primary key of an existing row.

Load 选项Load Option 说明Description
PreserveChanges(默认值)PreserveChanges (default) 用传入行的值更新行的原始版本。Updates the original version of the row with the value of the incoming row.
OverwriteChanges 用传入行的值更新行的当前版本和原始版本。Updates the current and original versions of the row with the value of the incoming row.
Upsert 用传入行的值更新行的当前版本。Updates the current version of the row with the value of the incoming row.

通常, PreserveChangesOverwriteChanges选项适用于用户需要与主数据源同步及其更改的DataSet情况。In general, the PreserveChanges and OverwriteChanges options are intended for scenarios in which the user needs to synchronize the DataSet and its changes with the primary data source. Upsert选项有助于聚合来自一个或多个辅助数据源的更改。The Upsert option facilitates aggregating changes from one or more secondary data sources.

Load(IDataReader, LoadOption, DataTable[]) Load(IDataReader, LoadOption, DataTable[]) Load(IDataReader, LoadOption, DataTable[])

使用提供的 DataSet 以数据源的值填充 IDataReader,同时使用 DataTable 实例的数组提供架构和命名空间信息。Fills a DataSet with values from a data source using the supplied IDataReader, using an array of DataTable instances to supply the schema and namespace information.

public:
 void Load(System::Data::IDataReader ^ reader, System::Data::LoadOption loadOption, ... cli::array <System::Data::DataTable ^> ^ tables);
public void Load (System.Data.IDataReader reader, System.Data.LoadOption loadOption, params System.Data.DataTable[] tables);
member this.Load : System.Data.IDataReader * System.Data.LoadOption * System.Data.DataTable[] -> unit

参数

reader
IDataReader IDataReader IDataReader

提供一个或多个结果集的 IDataReaderAn IDataReader that provides one or more result sets.

loadOption
LoadOption LoadOption LoadOption

一个来自 LoadOption 枚举的值,该值指示 DataTable 中的 DataSet 实例内已有的行如何与共享同一主键的传入行进行组合。A value from the LoadOption enumeration that indicates how rows already in the DataTable instances within the DataSet will be combined with incoming rows that share the same primary key.

tables
DataTable[]

DataTable 实例的数组,Load(IDataReader, LoadOption, DataTable[]) 方法从该数组中检索名称和命名空间信息。An array of DataTable instances, from which the Load(IDataReader, LoadOption, DataTable[]) method retrieves name and namespace information. 其中每个表都必须是此 DataTableCollection 所包含的 DataSet 的成员。Each of these tables must be a member of the DataTableCollection contained by this DataSet.

示例

下面的示例创建一个新DataSet的,将DataTable两个实例DataSet添加到,然后DataSet使用Load方法(从DataTableReader包含两个结果集的中检索数据)填充。The following example creates a new DataSet, adds two DataTable instances to the DataSet, and then fills the DataSet using the Load method, retrieving data from a DataTableReader that contains two result sets. 最后,该示例在控制台窗口中显示表的内容。Finally, the example displays the contents of the tables in the console window.

static void Main()
{
    DataSet dataSet = new DataSet();

    DataTable customerTable = new DataTable();
    DataTable productTable = new DataTable();

    // This information is cosmetic, only.
    customerTable.TableName = "Customers";
    productTable.TableName = "Products";

    // Add the tables to the DataSet:
    dataSet.Tables.Add(customerTable);
    dataSet.Tables.Add(productTable);

    // Load the data into the existing DataSet. 
    DataTableReader reader = GetReader();
    dataSet.Load(reader, LoadOption.OverwriteChanges,
        customerTable, productTable);

    // Print out the contents of each table:
    foreach (DataTable table in dataSet.Tables)
    {
        PrintColumns(table);
    }

    Console.WriteLine("Press any key to continue.");
    Console.ReadKey();
}

private static DataTable GetCustomers()
{
    // Create sample Customers table.
    DataTable table = new DataTable();
    table.TableName = "Customers";

    // Create two columns, ID and Name.
    DataColumn idColumn = table.Columns.Add("ID", typeof(int));
    table.Columns.Add("Name", typeof(string));

    // Set the ID column as the primary key column.
    table.PrimaryKey = new DataColumn[] { idColumn };

    table.Rows.Add(new object[] { 0, "Mary" });
    table.Rows.Add(new object[] { 1, "Andy" });
    table.Rows.Add(new object[] { 2, "Peter" });
    table.AcceptChanges();
    return table;
}

private static DataTable GetProducts()
{
    // Create sample Products table.
    DataTable table = new DataTable();
    table.TableName = "Products";

    // Create two columns, ID and Name.
    DataColumn idColumn = table.Columns.Add("ID",
        typeof(int));
    table.Columns.Add("Name", typeof(string));

    // Set the ID column as the primary key column.
    table.PrimaryKey = new DataColumn[] { idColumn };

    table.Rows.Add(new object[] { 0, "Wireless Network Card" });
    table.Rows.Add(new object[] { 1, "Hard Drive" });
    table.Rows.Add(new object[] { 2, "Monitor" });
    table.Rows.Add(new object[] { 3, "CPU" });
    table.AcceptChanges();
    return table;
}

private static void PrintColumns(DataTable table)
{
    Console.WriteLine();
    Console.WriteLine(table.TableName);
    Console.WriteLine("=========================");
    // Loop through all the rows in the table:
    foreach (DataRow row in table.Rows)
    {
        for (int i = 0; i < table.Columns.Count; i++)
        {
            Console.Write(row[i] + " ");
        }
        Console.WriteLine();
    }
}

private static DataTableReader GetReader()
{
    // Return a DataTableReader containing multiple
    // result sets, just for the sake of this demo.
    DataSet dataSet = new DataSet();
    dataSet.Tables.Add(GetCustomers());
    dataSet.Tables.Add(GetProducts());
    return dataSet.CreateDataReader();
}
Sub Main()
    Dim dataSet As New DataSet

    Dim customerTable As New DataTable
    Dim productTable As New DataTable

    ' This information is cosmetic, only.
    customerTable.TableName = "Customers"
    productTable.TableName = "Products"

    ' Add the tables to the DataSet:
    dataSet.Tables.Add(customerTable)
    dataSet.Tables.Add(productTable)

    ' Load the data into the existing DataSet. 
    Dim reader As DataTableReader = GetReader()
    dataSet.Load(reader, LoadOption.OverwriteChanges, _
        customerTable, productTable)

    ' Print out the contents of each table:
    For Each table As DataTable In dataSet.Tables
        PrintColumns(table)
    Next

    Console.WriteLine("Press any key to continue.")
    Console.ReadKey()
End Sub

Private Function GetCustomers() As DataTable
    ' Create sample Customers table.
    Dim table As New DataTable
    table.TableName = "Customers"

    ' Create two columns, ID and Name.
    Dim idColumn As DataColumn = table.Columns.Add("ID", _
        GetType(Integer))
    table.Columns.Add("Name", GetType(String))

    ' Set the ID column as the primary key column.
    table.PrimaryKey = New DataColumn() {idColumn}

    table.Rows.Add(New Object() {0, "Mary"})
    table.Rows.Add(New Object() {1, "Andy"})
    table.Rows.Add(New Object() {2, "Peter"})
    table.AcceptChanges()
    Return table
End Function

Private Function GetProducts() As DataTable
    ' Create sample Products table, in order
    ' to demonstrate the behavior of the DataTableReader.
    Dim table As New DataTable
    table.TableName = "Products"

    ' Create two columns, ID and Name.
    Dim idColumn As DataColumn = table.Columns.Add("ID", _
        GetType(Integer))
    table.Columns.Add("Name", GetType(String))

    ' Set the ID column as the primary key column.
    table.PrimaryKey = New DataColumn() {idColumn}

    table.Rows.Add(New Object() {0, "Wireless Network Card"})
    table.Rows.Add(New Object() {1, "Hard Drive"})
    table.Rows.Add(New Object() {2, "Monitor"})
    table.Rows.Add(New Object() {3, "CPU"})
    Return table
End Function

Private Function GetReader() As DataTableReader
    ' Return a DataTableReader containing multiple
    ' result sets, just for the sake of this demo.
    Dim dataSet As New DataSet
    dataSet.Tables.Add(GetCustomers())
    dataSet.Tables.Add(GetProducts())
    Return dataSet.CreateDataReader()
End Function

Private Sub PrintColumns( _
   ByVal table As DataTable)

    Console.WriteLine()
    Console.WriteLine(table.TableName)
    Console.WriteLine("=========================")
    ' Loop through all the rows in the table.
    For Each row As DataRow In table.Rows
        For Each col As DataColumn In table.Columns
            Console.Write(row(col).ToString() & " ")
        Next
        Console.WriteLine()
    Next
End Sub

注解

方法提供了一种方法,用于填充DataTableIDataReader实例中检索到的单个数据。 LoadThe Load method provides a technique for filling a single DataTable with data, retrieved from an IDataReader instance. 此方法提供了相同的功能,但允许你将中的多个结果IDataReader集加载到DataSet中的多个表中。This method provides the same functionality, but allows you to load multiple result sets from an IDataReader into multiple tables within a DataSet.

备注

InvalidOperationException如果传入reader的任何源数据列是计算列,则加载操作将失败,并出现。The load operation will fail with an InvalidOperationException if any of the source data columns in the incoming reader are computed columns.

参数允许你指定导入的数据与现有数据交互的方式,并且可以是LoadOption枚举中的任何值。 loadOptionThe loadOption parameter allows you to specify how you want the imported data to interact with existing data, and can be any of the values from the LoadOption enumeration. 有关使用此参数的DataTable详细信息,请参阅Load方法的文档。See the documentation for the DataTableLoad method for more information on using this parameter.

使用tables参数可以指定DataTable实例的数组,指示对应于从读取器加载的每个结果集的表的顺序。The tables parameter allows you to specify an array of DataTable instances, indicating the order of the tables corresponding to each result set loaded from the reader. 方法使用来自源数据DataTable读取器的单个结果集中的数据填充每个提供的实例。 LoadThe Load method fills each supplied DataTable instance with data from a single result set from the source data reader. 在每个结果集之后Load ,该方法将移到读取器内的下一个结果集,直到没有更多的结果集。After each result set, the Load method moves on to the next result set within the reader, until there are no more result sets.

此方法的名称解析方案与后跟Fill DbDataAdapter类的方法的名称解析方案相同。The name resolution scheme for this method is the same as that followed by the Fill method of the DbDataAdapter class.

另请参阅

Load(IDataReader, LoadOption, String[]) Load(IDataReader, LoadOption, String[]) Load(IDataReader, LoadOption, String[])

使用所提供的 DataSet,并使用字符串数组为 DataSet 中的表提供名称,从而用来自数据源的值填充 IDataReaderFills a DataSet with values from a data source using the supplied IDataReader, using an array of strings to supply the names for the tables within the DataSet.

public:
 void Load(System::Data::IDataReader ^ reader, System::Data::LoadOption loadOption, ... cli::array <System::String ^> ^ tables);
public void Load (System.Data.IDataReader reader, System.Data.LoadOption loadOption, params string[] tables);
member this.Load : System.Data.IDataReader * System.Data.LoadOption * string[] -> unit

参数

reader
IDataReader IDataReader IDataReader

提供一个或多个结果集的 IDataReaderAn IDataReader that provides one or more result sets.

loadOption
LoadOption LoadOption LoadOption

一个来自 LoadOption 枚举的值,该值指示 DataTable 中的 DataSet 实例内已有的行如何与共享同一主键的传入行进行组合。A value from the LoadOption enumeration that indicates how rows already in the DataTable instances within the DataSet will be combined with incoming rows that share the same primary key.

tables
String[]

字符串数组,Load 方法将从该数组中检索表名称信息。An array of strings, from which the Load method retrieves table name information.

示例

下面的控制台应用程序示例首先DataSet Load使用方法创建表,并将数据从读取器加载到中。The following Console application example first creates tables and loads data from a reader into a DataSet, using the Load method. 然后,该示例向添加表DataSet ,并尝试使用DataTableReader中的数据填充表。The example then adds tables to a DataSet and attempts to fill the tables with data from a DataTableReader. 在此示例中,由于传递给Load方法的参数指示不存在的表名,因此该Load方法会创建一个新表来匹配作为参数传递的名称。In this example, because the parameters passed to the Load method indicate a table name that does not exist, the Load method creates a new table to match the name passed as a parameter. 加载数据后,该示例会在控制台窗口中显示其所有表的内容。Once the data has been loaded, the example displays the contents of all its tables in the Console window.

static void Main()
{
    DataSet dataSet = new DataSet();

    DataTableReader reader = GetReader();

    // The tables listed as parameters for the Load method 
    // should be in the same order as the tables within the IDataReader.
    dataSet.Load(reader, LoadOption.Upsert, "Customers", "Products");
    foreach (DataTable table in dataSet.Tables)
    {
        PrintColumns(table);
    }

    // Now try the example with the DataSet
    // already filled with data:
    dataSet = new DataSet();
    dataSet.Tables.Add(GetCustomers());
    dataSet.Tables.Add(GetProducts());

    // Retrieve a data reader containing changed data:
    reader = GetReader();

    // Load the data into the existing DataSet. Retrieve the order of the
    // the data in the reader from the
    // list of table names in the parameters. If you specify
    // a new table name here, the Load method will create
    // a corresponding new table.
    dataSet.Load(reader, LoadOption.Upsert, 
        "NewCustomers", "Products");
    foreach (DataTable table in dataSet.Tables)
    {
        PrintColumns(table);
    }

    Console.WriteLine("Press any key to continue.");
    Console.ReadKey();
}

private static DataTable GetCustomers()
{
    // Create sample Customers table.
    DataTable table = new DataTable();
    table.TableName = "Customers";

    // Create two columns, ID and Name.
    DataColumn idColumn = table.Columns.Add("ID", typeof(int));
    table.Columns.Add("Name", typeof(string));

    // Set the ID column as the primary key column.
    table.PrimaryKey = new DataColumn[] { idColumn };

    table.Rows.Add(new object[] { 0, "Mary" });
    table.Rows.Add(new object[] { 1, "Andy" });
    table.Rows.Add(new object[] { 2, "Peter" });
    table.AcceptChanges();
    return table;
}

private static DataTable GetProducts()
{
    // Create sample Products table.
    DataTable table = new DataTable();
    table.TableName = "Products";

    // Create two columns, ID and Name.
    DataColumn idColumn = table.Columns.Add("ID", typeof(int));
    table.Columns.Add("Name", typeof(string));

    // Set the ID column as the primary key column.
    table.PrimaryKey = new DataColumn[] { idColumn };

    table.Rows.Add(new object[] { 0, "Wireless Network Card" });
    table.Rows.Add(new object[] { 1, "Hard Drive" });
    table.Rows.Add(new object[] { 2, "Monitor" });
    table.Rows.Add(new object[] { 3, "CPU" });
    table.AcceptChanges();
    return table;
}

private static void PrintColumns(DataTable table)
{
    Console.WriteLine();
    Console.WriteLine(table.TableName);
    Console.WriteLine("=========================");
    // Loop through all the rows in the table:
    foreach (DataRow row in table.Rows)
    {
        for (int i = 0; i < table.Columns.Count; i++)
        {
            Console.Write(row[i] + " ");
        }
        Console.WriteLine();
    }
}

private static DataTableReader GetReader()
{
    // Return a DataTableReader containing multiple
    // result sets, just for the sake of this demo.
    DataSet dataSet = new DataSet();
    dataSet.Tables.Add(GetCustomers());
    dataSet.Tables.Add(GetProducts());
    return dataSet.CreateDataReader();
}
Sub Main()
  Dim dataSet As New DataSet
  Dim table As DataTable

  Dim reader As DataTableReader = GetReader()

  ' The tables listed as parameters for the Load method 
  ' should be in the same order as the tables within the IDataReader.
  dataSet.Load(reader, LoadOption.Upsert, "Customers", "Products")
  For Each table In dataSet.Tables
    PrintColumns(table)
  Next

  ' Now try the example with the DataSet
  ' already filled with data:
  dataSet = New DataSet
  dataSet.Tables.Add(GetCustomers())
  dataSet.Tables.Add(GetProducts())

  ' Retrieve a data reader containing changed data:
  reader = GetReader()

  ' Load the data into the existing DataSet. Retrieve the order of the
  ' the data in the reader from the
  ' list of table names in the parameters. If you specify
  ' a new table name here, the Load method will create
  ' a corresponding new table.
  dataSet.Load(reader, LoadOption.Upsert, "NewCustomers", "Products")
  For Each table In dataSet.Tables
    PrintColumns(table)
  Next

  Console.WriteLine("Press any key to continue.")
  Console.ReadKey()
End Sub

Private Function GetCustomers() As DataTable
  ' Create sample Customers table.
  Dim table As New DataTable
  table.TableName = "Customers"

  ' Create two columns, ID and Name.
  Dim idColumn As DataColumn = table.Columns.Add("ID", GetType(Integer))
  table.Columns.Add("Name", GetType(String))

  ' Set the ID column as the primary key column.
  table.PrimaryKey = New DataColumn() {idColumn}

  table.Rows.Add(New Object() {0, "Mary"})
  table.Rows.Add(New Object() {1, "Andy"})
  table.Rows.Add(New Object() {2, "Peter"})
  table.AcceptChanges()
  Return table
End Function

Private Function GetProducts() As DataTable
  ' Create sample Products table, in order
  ' to demonstrate the behavior of the DataTableReader.
  Dim table As New DataTable
  table.TableName = "Products"

  ' Create two columns, ID and Name.
  Dim idColumn As DataColumn = table.Columns.Add("ID", GetType(Integer))
  table.Columns.Add("Name", GetType(String))

  ' Set the ID column as the primary key column.
  table.PrimaryKey = New DataColumn() {idColumn}

  table.Rows.Add(New Object() {0, "Wireless Network Card"})
  table.Rows.Add(New Object() {1, "Hard Drive"})
  table.Rows.Add(New Object() {2, "Monitor"})
  table.Rows.Add(New Object() {3, "CPU"})
  Return table
End Function

Private Function GetReader() As DataTableReader
  ' Return a DataTableReader containing multiple
  ' result sets, just for the sake of this demo.
  Dim dataSet As New DataSet
  dataSet.Tables.Add(GetCustomers())
  dataSet.Tables.Add(GetProducts())
  Return dataSet.CreateDataReader()
End Function

Private Sub PrintColumns( _
   ByVal table As DataTable)

  Console.WriteLine()
  Console.WriteLine(table.TableName)
  Console.WriteLine("=========================")
  ' Loop through all the rows in the table.
  For Each row As DataRow In table.Rows
    For Each col As DataColumn In table.Columns
      Console.Write(row(col).ToString() & " ")
    Next
    Console.WriteLine()
  Next
End Sub

注解

方法提供了一种方法,用于填充DataTableIDataReader实例中检索到的单个数据。 LoadThe Load method provides a technique for filling a single DataTable with data, retrieved from an IDataReader instance. 此方法提供了相同的功能,但允许你将中的多个结果IDataReader集加载到DataSet中的多个表中。This method provides the same functionality, but allows you to load multiple result sets from an IDataReader into multiple tables within a DataSet.

备注

InvalidOperationException如果传入reader的任何源数据列是计算列,则加载操作将失败,并出现。The load operation will fail with an InvalidOperationException if any of the source data columns in the incoming reader are computed columns.

参数允许你指定导入的数据与现有数据交互的方式,并且可以是LoadOption枚举中的任何值。 loadOptionThe loadOption parameter allows you to specify how you want the imported data to interact with existing data, and can be any of the values from the LoadOption enumeration. 有关使用此参数的Load详细信息,请参阅方法的文档。See the documentation for the Load method for more information on using this parameter.

使用tables参数可以指定表名的数组,指示与从读取器加载的每个结果集对应的表的顺序。The tables parameter allows you to specify an array of table names, indicating the order of the tables corresponding to each result set loaded from the reader. 方法尝试在与表名称数组中找到DataSet的名称匹配的表中查找匹配项。 LoadThe Load method attempts to find a table within the DataSet matching the name found in the array of table names, in order. 如果找到匹配的表,则将使用当前结果集的内容加载该表。If a matching table is found, that table is loaded with the content of the current result set. 如果未找到匹配的表,则使用表名数组中提供的名称创建一个表,并从结果集中推断新表的架构。If no matching table is found, a table is created using the name supplied in the array of table names, and the new table's schema is inferred from the result set. 在每个结果集之后Load ,该方法将移到读取器内的下一个结果集,直到没有更多的结果集。After each result set, the Load method moves on to the next result set within the reader, until there are no more result sets.

DataSet关联的默认命名空间(如果有)与每个新创建DataTable的关联。The default namespace associated with DataSet, if any, is associated with each newly created DataTable. 此方法的名称解析方案与后跟Fill DbDataAdapter类的方法的名称解析方案相同。The name resolution scheme for this method is the same as that followed by the Fill method of the DbDataAdapter class.

另请参阅

Load(IDataReader, LoadOption, FillErrorEventHandler, DataTable[]) Load(IDataReader, LoadOption, FillErrorEventHandler, DataTable[]) Load(IDataReader, LoadOption, FillErrorEventHandler, DataTable[])

使用提供的 DataSet 以数据源的值填充 IDataReader,同时使用 DataTable 实例的数组提供架构和命名空间信息。Fills a DataSet with values from a data source using the supplied IDataReader, using an array of DataTable instances to supply the schema and namespace information.

public:
 virtual void Load(System::Data::IDataReader ^ reader, System::Data::LoadOption loadOption, System::Data::FillErrorEventHandler ^ errorHandler, ... cli::array <System::Data::DataTable ^> ^ tables);
public virtual void Load (System.Data.IDataReader reader, System.Data.LoadOption loadOption, System.Data.FillErrorEventHandler errorHandler, params System.Data.DataTable[] tables);
abstract member Load : System.Data.IDataReader * System.Data.LoadOption * System.Data.FillErrorEventHandler * System.Data.DataTable[] -> unit
override this.Load : System.Data.IDataReader * System.Data.LoadOption * System.Data.FillErrorEventHandler * System.Data.DataTable[] -> unit

参数

reader
IDataReader IDataReader IDataReader

提供一个或多个结果集的 IDataReaderAn IDataReader that provides one or more result sets.

loadOption
LoadOption LoadOption LoadOption

一个来自 LoadOption 枚举的值,该值指示 DataTable 中的 DataSet 实例内已有的行如何与共享同一主键的传入行进行组合。A value from the LoadOption enumeration that indicates how rows already in the DataTable instances within the DataSet will be combined with incoming rows that share the same primary key.

errorHandler
FillErrorEventHandler FillErrorEventHandler FillErrorEventHandler

加载数据时出现错误的情况下要调用的 FillErrorEventHandler 委托。A FillErrorEventHandler delegate to call when an error occurs while loading data.

tables
DataTable[]

DataTable 实例的数组,Load(IDataReader, LoadOption, FillErrorEventHandler, DataTable[]) 方法从该数组中检索名称和命名空间信息。An array of DataTable instances, from which the Load(IDataReader, LoadOption, FillErrorEventHandler, DataTable[]) method retrieves name and namespace information.

示例

下面的示例将一个表添加到DataSet,然后尝试Load使用方法从包含不兼容架构的中DataTableReader加载数据。The following example adds a table to a DataSet, and then attempts to use the Load method to load data from a DataTableReader that contains an incompatible schema. 此示例使用FillErrorEventHandler委托来调查并处理错误,而不是捕获错误。Rather than trapping the error, this example uses a FillErrorEventHandler delegate to investigate and handle the error. 输出显示在控制台窗口中。The output is displayed in the console window.

static void Main()
{
    // Attempt to load data from a data reader in which
    // the schema is incompatible with the current schema.
    // If you use exception handling, you won't get the chance
    // to examine each row, and each individual table,
    // as the Load method progresses.
    // By taking advantage of the FillErrorEventHandler delegate,
    // you can interact with the Load process as an error occurs,
    // attempting to fix the problem, or simply continuing or quitting
    // the Load process.:
    DataSet dataSet = new DataSet();
    DataTable table = GetIntegerTable();
    dataSet.Tables.Add(table);
    DataTableReader reader = new DataTableReader(GetStringTable());
    dataSet.Load(reader, LoadOption.OverwriteChanges, 
        FillErrorHandler, table);

    Console.WriteLine("Press any key to continue.");
    Console.ReadKey();
}

private static DataTable GetIntegerTable()
{
    // Create sample Customers table, in order
    // to demonstrate the behavior of the DataTableReader.
    DataTable table = new DataTable();

    // Create two columns, ID and Name.
    DataColumn idColumn = table.Columns.Add("ID", typeof(int));

    // Set the ID column as the primary key column.
    table.PrimaryKey = new DataColumn[] { idColumn };

    table.Rows.Add(new object[] { 4 });
    table.Rows.Add(new object[] { 5 });
    table.AcceptChanges();
    return table;
}

private static DataTable GetStringTable()
{
    // Create sample Customers table, in order
    // to demonstrate the behavior of the DataTableReader.
    DataTable table = new DataTable();

    // Create two columns, ID and Name.
    DataColumn idColumn = table.Columns.Add("ID", typeof(string));

    // Set the ID column as the primary key column.
    table.PrimaryKey = new DataColumn[] { idColumn };

    table.Rows.Add(new object[] { "Mary" });
    table.Rows.Add(new object[] { "Andy" });
    table.Rows.Add(new object[] { "Peter" });
    table.AcceptChanges();
    return table;
}

static void FillErrorHandler(object sender, FillErrorEventArgs e)
{
    // You can use the e.Errors value to determine exactly what
    // went wrong.
    if (e.Errors.GetType() == typeof(System.FormatException))
    {
        Console.WriteLine("Error when attempting to update the value: {0}", 
            e.Values[0]);
    }

    // Setting e.Continue to True tells the Load
    // method to continue trying. Setting it to False
    // indicates that an error has occurred, and the 
    // Load method raises the exception that got 
    // you here.
    e.Continue = true;
}
Sub Main()
  Dim dataSet As New DataSet
  Dim table As New DataTable()

  ' Attempt to load data from a data reader in which
  ' the schema is incompatible with the current schema.
  ' If you use exception handling, you won't get the chance
  ' to examine each row, and each individual table,
  ' as the Load method progresses.
  ' By taking advantage of the FillErrorEventHandler delegate,
  ' you can interact with the Load process as an error occurs,
  ' attempting to fix the problem, or simply continuing or quitting
  ' the Load process.:
  dataSet = New DataSet()
  table = GetIntegerTable()
  dataSet.Tables.Add(table)
  Dim reader As New DataTableReader(GetStringTable())
  dataSet.Load(reader, LoadOption.OverwriteChanges, _
      AddressOf FillErrorHandler, table)

  Console.WriteLine("Press any key to continue.")
  Console.ReadKey()
End Sub

Private Sub FillErrorHandler(ByVal sender As Object, _
  ByVal e As FillErrorEventArgs)
  ' You can use the e.Errors value to determine exactly what
  ' went wrong.
  If e.Errors.GetType Is GetType(System.FormatException) Then
    Console.WriteLine("Error when attempting to update the value: {0}", _
      e.Values(0))
  End If

  ' Setting e.Continue to True tells the Load
  ' method to continue trying. Setting it to False
  ' indicates that an error has occurred, and the 
  ' Load method raises the exception that got 
  ' you here.
  e.Continue = True
End Sub

Private Function GetIntegerTable() As DataTable
  ' Create sample table with a single Int32 column.
  Dim table As New DataTable

  Dim idColumn As DataColumn = table.Columns.Add("ID", _
      GetType(Integer))

  ' Set the ID column as the primary key column.
  table.PrimaryKey = New DataColumn() {idColumn}

  table.Rows.Add(New Object() {4})
  table.Rows.Add(New Object() {5})
  table.TableName = "IntegerTable"
  table.AcceptChanges()
  Return table
End Function

Private Function GetStringTable() As DataTable
  ' Create sample table with a single String column.
  Dim table As New DataTable

  Dim idColumn As DataColumn = table.Columns.Add("ID", _
      GetType(String))

  ' Set the ID column as the primary key column.
  table.PrimaryKey = New DataColumn() {idColumn}

  table.Rows.Add(New Object() {"Mary"})
  table.Rows.Add(New Object() {"Andy"})
  table.Rows.Add(New Object() {"Peter"})
  table.AcceptChanges()
  Return table
End Function

Private Sub PrintColumns( _
   ByVal table As DataTable)

  ' Loop through all the rows in the DataTableReader.
  For Each row As DataRow In table.Rows
    For Each col As DataColumn In table.Columns
      Console.Write(row(col).ToString() & " ")
    Next
    Console.WriteLine()
  Next
End Sub

注解

方法提供了一种方法,用于填充DataTableIDataReader实例中检索到的单个数据。 LoadThe Load method provides a technique for filling a single DataTable with data, retrieved from an IDataReader instance. 此方法提供了相同的功能,但允许你将中的多个结果IDataReader集加载到DataSet中的多个表中。This method provides the same functionality, but allows you to load multiple result sets from an IDataReader into multiple tables within a DataSet.

备注

InvalidOperationException如果传入reader的任何源数据列是计算列,则加载操作将失败,并出现。The load operation will fail with an InvalidOperationException if any of the source data columns in the incoming reader are computed columns.

参数允许你指定导入的数据与现有数据交互的方式,并且可以是LoadOption枚举中的任何值。 loadOptionThe loadOption parameter allows you to specify how you want the imported data to interact with existing data, and can be any of the values from the LoadOption enumeration. 有关使用此参数的DataTable详细信息,请参阅Load方法的文档。See the documentation for the DataTableLoad method for more information on using this parameter.

参数是一个FillErrorEventHandler委托,该委托引用在加载数据的过程中发生错误时调用的过程。 errorHandlerThe errorHandler parameter is a FillErrorEventHandler delegate that refers to a procedure that is called when an error occurs while loading data. 传递给过程的DataTable 参数提供了属性,这些属性可用于检索有关所发生错误的信息、当前数据行以及要填充的。FillErrorEventArgsThe FillErrorEventArgs parameter passed to the procedure provides properties that allow you to retrieve information about the error that occurred, the current row of data, and the DataTable being filled. 使用此委托机制(而不是更简单的 try/catch 块),可以确定错误,处理情况,并根据需要继续处理。Using this delegate mechanism, rather than a simpler try/catch block, allows you to determine the error, handle the situation, and continue processing if you like. 参数提供属性:将此属性设置为true ,以指示你已处理错误并希望继续处理; 将属性设置为false ,以指示你希望暂停处理。 Continue FillErrorEventArgsThe FillErrorEventArgs parameter supplies a Continue property: set this property to true to indicate that you have handled the error and wish to continue processing; set the property to false to indicate that you wish to halt processing. 请注意,将属性设置为false会导致触发问题的代码引发异常。Be aware that setting the property to false causes the code that triggered the problem to throw an exception.

使用tables参数可以指定DataTable实例的数组,指示对应于从读取器加载的每个结果集的表的顺序。The tables parameter allows you to specify an array of DataTable instances, indicating the order of the tables corresponding to each result set loaded from the reader. 方法使用来自源数据DataTable读取器的单个结果集中的数据填充每个提供的实例。 LoadThe Load method fills each supplied DataTable instance with data from a single result set from the source data reader. 在每个结果集之后Load ,该方法将移到读取器内的下一个结果集,直到没有更多的结果集。After each result set, the Load method moves on to the next result set within the reader, until there are no more result sets.

此方法的名称解析方案与后跟Fill DbDataAdapter类的方法的名称解析方案相同。The name resolution scheme for this method is the same as that followed by the Fill method of the DbDataAdapter class.

另请参阅

适用于