DbDataAdapter.Update 方法

定义

通过为 DataSet 中的每个已插入、已更新或已删除的行执行相应的 INSERT、UPDATE 或 DELETE 语句来更新数据库中的值。Updates the values in the database by executing the respective INSERT, UPDATE, or DELETE statements for each inserted, updated, or deleted row in the DataSet.

重载

Update(DataSet, String)

通过为具有指定名称 DataSetDataTable 中的每个已插入、已更新或已删除的行执行相应的 INSERT、UPDATE 或 DELETE 语句来更新数据库中的值。Updates the values in the database by executing the respective INSERT, UPDATE, or DELETE statements for each inserted, updated, or deleted row in the DataSet with the specified DataTable name.

Update(DataRow[], DataTableMapping)

通过为指定的 DataSet 对象数组中的每个已插入、已更新或已删除的行执行相应的 INSERT、UPDATE 或 DELETE 语句来更新数据库中的值。Updates the values in the database by executing the respective INSERT, UPDATE, or DELETE statements for each inserted, updated, or deleted row in the specified array of DataSet objects.

Update(DataTable)

通过为指定的 DataTable 中的每个已插入、已更新或已删除的行执行相应的 INSERT、UPDATE 或 DELETE 语句来更新数据库中的值。Updates the values in the database by executing the respective INSERT, UPDATE, or DELETE statements for each inserted, updated, or deleted row in the specified DataTable.

Update(DataSet)

通过为指定的 DataSet 中的每个已插入、已更新或已删除的行执行相应的 INSERT、UPDATE 或 DELETE 语句来更新数据库中的值。Updates the values in the database by executing the respective INSERT, UPDATE, or DELETE statements for each inserted, updated, or deleted row in the specified DataSet.

Update(DataRow[])

通过为 DataSet 中的指定数组中的每个已插入、已更新或已删除的行执行相应的 INSERT、UPDATE 或 DELETE 语句来更新数据库中的值。Updates the values in the database by executing the respective INSERT, UPDATE, or DELETE statements for each inserted, updated, or deleted row in the specified array in the DataSet.

Update(DataSet, String)

通过为具有指定名称 DataSetDataTable 中的每个已插入、已更新或已删除的行执行相应的 INSERT、UPDATE 或 DELETE 语句来更新数据库中的值。Updates the values in the database by executing the respective INSERT, UPDATE, or DELETE statements for each inserted, updated, or deleted row in the DataSet with the specified DataTable name.

public:
 int Update(System::Data::DataSet ^ dataSet, System::String ^ srcTable);
public int Update (System.Data.DataSet dataSet, string srcTable);
override this.Update : System.Data.DataSet * string -> int
Public Function Update (dataSet As DataSet, srcTable As String) As Integer

参数

dataSet
DataSet

用于更新数据源的 DataSetThe DataSet to use to update the data source.

srcTable
String

用于表映射的源表的名称。The name of the source table to use for table mapping.

返回

Int32

DataSet 中成功更新的行数。The number of rows successfully updated from the DataSet.

例外

DataSet 无效。The DataSet is invalid.

源表无效。The source table is invalid.

尝试执行 INSERT、UPDATE 或 DELETE 语句,但没有记录受到影响。An attempt to execute an INSERT, UPDATE, or DELETE statement resulted in zero records affected.

示例

下面的示例使用派生类 OleDbDataAdapter 来更新数据源。The following example uses the derived class, OleDbDataAdapter, to update the data source.

public DataSet CreateCmdsAndUpdate(string connectionString,
    string queryString, string tableName)
{
    using (OleDbConnection connection = new OleDbConnection(connectionString))
    {
        OleDbDataAdapter adapter = new OleDbDataAdapter();
        adapter.SelectCommand = new OleDbCommand(queryString, connection);
        OleDbCommandBuilder builder = new OleDbCommandBuilder(adapter);

        connection.Open();

        DataSet customers = new DataSet();
        adapter.Fill(customers);

        //code to modify data in dataset here

        adapter.Update(customers, tableName);

        return customers;
    }
}
Public Function CreateCmdsAndUpdate(ByVal connectionString As String, _
    ByVal queryString As String, _
    ByVal tableName As String) As DataSet

    Using connection As New OleDbConnection(connectionString)
        Dim adapter As New OleDbDataAdapter()
        adapter.SelectCommand = New OleDbCommand(queryString, connection)
        Dim builder As New OleDbCommandBuilder(adapter)

        connection.Open()

        Dim customers As New DataSet()
        adapter.Fill(customers)

        ' Code to modify data in DataSet here 

        adapter.Update(customers, tableName)

        Return customers
    End Using
End Function

注解

当应用程序调用 Update 方法时,将 DbDataAdapter 检查 RowState 属性,并根据中配置的索引的顺序,对每个行重复执行所需的 INSERT、UPDATE 或 DELETE 语句 DataSetWhen an application calls the Update method, the DbDataAdapter examines the RowState property, and executes the required INSERT, UPDATE, or DELETE statements iteratively for each row, based on the order of the indexes configured in the DataSet. 例如, Update 可能会执行 DELETE 语句,后跟 INSERT 语句,然后执行另一 delete 语句,因为中的行的顺序 DataTableFor example, Update might execute a DELETE statement, followed by an INSERT statement, and then another DELETE statement, due to the ordering of the rows in the DataTable.

应注意的是,这些语句不作为批处理执行;每一行都单独更新。It should be noted that these statements are not performed as a batch process; each row is updated individually. 应用程序可以 GetChanges 在以下情况下调用方法:在此情况下,必须控制语句类型的序列 (例如,在 UPDATE) 之前插入。An application can call the GetChanges method in situations where you must control the sequence of statement types (for example, INSERT before UPDATE). 有关详细信息,请参阅 用 Dataadapter 更新数据源For more information, see Updating Data Sources with DataAdapters.

如果尚未指定 INSERT、UPDATE 或 DELETE 语句,则该方法将 Update 生成一个异常。If INSERT, UPDATE, or DELETE statements have not been specified, the Update method generates an exception. 但是, SqlCommandBuilder OleDbCommandBuilder 如果您设置了 SelectCommand .NET Framework 数据提供程序的属性,则可以创建或对象以自动为单表更新生成 SQL 语句。However, you can create a SqlCommandBuilder or OleDbCommandBuilder object to automatically generate SQL statements for single-table updates if you set the SelectCommand property of a .NET Framework data provider. 然后, CommandBuilder 将生成未设置的任何其他 SQL 语句。Then, any additional SQL statements that you do not set are generated by the CommandBuilder. 此代逻辑要求密钥列信息存在于中 DataSetThis generation logic requires key column information to be present in the DataSet. 有关详细信息,请参阅 通过 Commandbuilder 生成命令For more information see Generating Commands with CommandBuilders.

Update方法支持 DataSet 包含多个对象,这些 DataTable 对象的名称仅区分大小写。The Update method supports scenarios where the DataSet contains multiple DataTable objects whose names differ only by case. 如果有多个同名但大小写不同的表存在于中, DataSetUpdate 执行区分大小写的比较来查找相应的表,如果不存在精确匹配,则会生成异常。When multiple tables with the same name, but different case, exist in a DataSet, Update performs a case-sensitive comparison to find the corresponding table, and generates an exception if no exact match exists. 下面的 c # 代码阐释了这一行为。The following C# code illustrates this behavior.

DataSet ds = new DataSet();  
 ds.Tables.Add("aaa");  
 ds.Tables.Add("AAA");  
 adapter.Update(ds, "aaa"); // Updates "aaa", which already exists in the DataSet.  
 adapter.Update(ds, "AAA"); // Updates "AAA", which already exists in the DataSet.  
    adapter.Update(ds, "Aaa"); // Results in an exception.  

如果 Update 调用,并且 DataSet 仅包含 DataTable 其名称仅大小写不同的名称, DataTable 则会更新。If Update is called and the DataSet contains only one DataTable whose name differs only by case, that DataTable is updated. 在这种情况下,比较不区分大小写。In this scenario, the comparison is case insensitive. 下面的 c # 代码阐释了这一行为。The following C# code illustrates this behavior.

DataSet dataset = new DataSet();  
 dataset.Tables.Add("aaa");  
    adapter.Update(dataset, "AAA"); // Updates table "aaa" because only one similarly named table is in the DataSet.  

Update 执行更新之前,方法将从第一个映射中列出的表中检索行。The Update method retrieves rows from the table listed in the first mapping before performing an update. Update然后,使用属性的值刷新该行 UpdatedRowSourceThe Update then refreshes the row using the value of the UpdatedRowSource property. 将忽略返回的任何其他行。Any additional rows returned are ignored.

在将任何数据加载回后 DataSet ,将 OnRowUpdated 引发事件,从而允许用户检查已协调的 DataSet 行和该命令返回的任何输出参数。After any data is loaded back into the DataSet, the OnRowUpdated event is raised, allowing the user to inspect the reconciled DataSet row and any output parameters returned by the command. 成功更新行后,将接受对该行所做的更改。After a row updates successfully, the changes to that row are accepted.

使用时 Update ,执行顺序如下所示:When using Update, the order of execution is as follows:

  1. 中的值 DataRow 将被移动到参数值中。The values in the DataRow are moved to the parameter values.

  2. 引发 OnRowUpdating 事件。The OnRowUpdating event is raised.

  3. 命令执行。The command executes.

  4. 如果命令设置为 FirstReturnedRecord ,则将第一个返回的结果放置在中 DataRowIf the command is set to FirstReturnedRecord, then the first returned result is placed in the DataRow.

  5. 如果有输出参数,则将它们放在中 DataRowIf there are output parameters, they are placed in the DataRow.

  6. 引发 OnRowUpdated 事件。The OnRowUpdated event is raised.

  7. 调用 AcceptChangesAcceptChanges is called.

与关联的每个命令 DbDataAdapter 通常都具有与之关联的参数集合。Each command associated with the DbDataAdapter usually has a parameters collection associated with it. 通过 SourceColumn SourceVersion .NET Framework 数据提供程序的类的和属性,将参数映射到当前行 ParameterParameters are mapped to the current row through the SourceColumn and SourceVersion properties of a .NET Framework data provider's Parameter class. SourceColumn 引用 DataTable DbDataAdapter 用于获取当前行的参数值的列。SourceColumn refers to a DataTable column that the DbDataAdapter references to obtain parameter values for the current row.

SourceColumn 在应用了任何表映射之前引用未映射的列名称。SourceColumn refers to the unmapped column name before any table mappings have been applied. 如果 SourceColumn 引用不存在的列,则执行的操作取决于下列值之一 MissingMappingActionIf SourceColumn refers to a nonexistent column, the action taken depends on one of the following MissingMappingAction values.

枚举值Enumeration value 采取的操作Action taken
MissingMappingAction.Passthrough 如果不存在映射,请使用中的源列名称和表名称 DataSetUse the source column names and table names in the DataSet if no mapping is present.
MissingMappingAction.Ignore SystemException生成。A SystemException is generated. 当显式设置映射时,缺少输入参数的映射通常是由错误引起的。When the mappings are explicitly set, a missing mapping for an input parameter is usually the result of an error.
MissingMappingAction.Error SystemException生成。A SystemException is generated.

SourceColumn属性还可用于将输出或输入/输出参数的值映射回 DataSetThe SourceColumn property is also used to map the value for output or input/output parameters back to the DataSet. 如果引用不存在的列,则会生成异常。An exception is generated if it refers to a nonexistent column.

SourceVersion.NET Framework 数据提供程序的类的属性 Parameter 确定是使用列值的原始版本、当前版本还是建议的版本。The SourceVersion property of a .NET Framework data provider's Parameter class determines whether to use the Original, Current, or Proposed version of the column value. 此功能通常用于在 UPDATE 语句的 WHERE 子句中包含原始值,以检查是否存在开放式并发冲突。This capability is often used to include original values in the WHERE clause of an UPDATE statement to check for optimistic concurrency violations.

备注

如果在更新行时出现错误,则会引发异常并中止执行更新。If an error occurs while updating a row, an exception is thrown and execution of the update is discontinued. 若要在遇到错误时继续执行更新操作而不生成异常,请在 ContinueUpdateOnError 调用之前将属性设置为 true UpdateTo continue the update operation without generating exceptions when an error is encountered, set the ContinueUpdateOnError property to true before calling Update. 您还可以在 DataAdapter 事件内每行响应错误 RowUpdatedYou may also respond to errors on a per-row basis within the RowUpdated event of a DataAdapter. 若要继续执行更新操作而不在事件中生成异常 RowUpdated ,请将 Status 的属性设置 RowUpdatedEventArgsContinueTo continue the update operation without generating an exception within the RowUpdated event, set the Status property of the RowUpdatedEventArgs to Continue.

适用于

Update(DataRow[], DataTableMapping)

通过为指定的 DataSet 对象数组中的每个已插入、已更新或已删除的行执行相应的 INSERT、UPDATE 或 DELETE 语句来更新数据库中的值。Updates the values in the database by executing the respective INSERT, UPDATE, or DELETE statements for each inserted, updated, or deleted row in the specified array of DataSet objects.

protected:
 virtual int Update(cli::array <System::Data::DataRow ^> ^ dataRows, System::Data::Common::DataTableMapping ^ tableMapping);
protected virtual int Update (System.Data.DataRow[] dataRows, System.Data.Common.DataTableMapping tableMapping);
override this.Update : System.Data.DataRow[] * System.Data.Common.DataTableMapping -> int
Protected Overridable Function Update (dataRows As DataRow(), tableMapping As DataTableMapping) As Integer

参数

dataRows
DataRow[]

用于更新数据源的 DataRow 对象的数组。An array of DataRow objects used to update the data source.

tableMapping
DataTableMapping

要使用的 TableMappings 集合。The TableMappings collection to use.

返回

Int32

DataSet 中成功更新的行数。The number of rows successfully updated from the DataSet.

例外

DataSet 无效。The DataSet is invalid.

源表无效。The source table is invalid.

不存在要更新的 DataRowNo DataRow exists to update.

-or- 不存在要更新的 DataTableNo DataTable exists to update.

-or- 不存在要用作源的 DataSetNo DataSet exists to use as a source.

尝试执行 INSERT、UPDATE 或 DELETE 语句,但没有记录受到影响。An attempt to execute an INSERT, UPDATE, or DELETE statement resulted in zero records affected.

注解

当应用程序调用 Update 方法时,将 DbDataAdapter 检查 RowState 属性,并根据中配置的索引的顺序,对每个行重复执行所需的 INSERT、UPDATE 或 DELETE 语句 DataSetWhen an application calls the Update method, the DbDataAdapter examines the RowState property, and executes the required INSERT, UPDATE, or DELETE statements iteratively for each row, based on the order of the indexes configured in the DataSet. 例如, Update 可能会执行 DELETE 语句,后跟 INSERT 语句,然后执行另一 delete 语句,因为中的行的顺序 DataTableFor example, Update might execute a DELETE statement, followed by an INSERT statement, and then another DELETE statement, due to the ordering of the rows in the DataTable.

应注意的是,这些语句不作为批处理执行;每一行都单独更新。It should be noted that these statements are not performed as a batch process; each row is updated individually. 应用程序可以 GetChanges 在以下情况下调用方法:例如,必须控制语句类型的序列 (例如,在更新) 之前插入。An application can call the GetChanges method in situations where you must control the sequence of statement types (for example, INSERTs before UPDATEs). 有关详细信息,请参阅 用 Dataadapter 更新数据源For more information, see Updating Data Sources with DataAdapters.

如果尚未指定 INSERT、UPDATE 或 DELETE 语句,则该方法将 Update 生成一个异常。If INSERT, UPDATE, or DELETE statements have not been specified, the Update method generates an exception. 但是, SqlCommandBuilder OleDbCommandBuilder 如果您设置了 SelectCommand .NET Framework 数据提供程序的属性,则可以创建或对象以自动为单表更新生成 SQL 语句。However, you can create a SqlCommandBuilder or OleDbCommandBuilder object to automatically generate SQL statements for single-table updates if you set the SelectCommand property of a .NET Framework data provider. 然后, CommandBuilder 将生成未设置的任何其他 SQL 语句。Then, any additional SQL statements that you do not set are generated by the CommandBuilder. 此代逻辑要求密钥列信息存在于中 DataSetThis generation logic requires key column information to be present in the DataSet. 有关详细信息,请参阅 通过 Commandbuilder 生成命令For more information see Generating Commands with CommandBuilders.

Update 执行更新之前,方法将从第一个映射中列出的表中检索行。The Update method retrieves rows from the table listed in the first mapping before performing an update. Update然后,使用属性的值刷新该行 UpdatedRowSourceThe Update then refreshes the row using the value of the UpdatedRowSource property. 将忽略返回的任何其他行。Any additional rows returned are ignored.

在将任何数据加载回后 DataSet ,将 OnRowUpdated 引发事件,从而允许用户检查已协调的 DataSet 行和该命令返回的任何输出参数。After any data is loaded back into the DataSet, the OnRowUpdated event is raised, allowing the user to inspect the reconciled DataSet row and any output parameters returned by the command. 成功更新行后,将接受对该行所做的更改。After a row updates successfully, the changes to that row are accepted.

使用时 Update ,执行顺序如下所示:When using Update, the order of execution is as follows:

  1. 中的值 DataRow 将被移动到参数值中。The values in the DataRow are moved to the parameter values.

  2. 引发 OnRowUpdating 事件。The OnRowUpdating event is raised.

  3. 命令执行。The command executes.

  4. 如果命令设置为 FirstReturnedRecord ,则将第一个返回的结果放置在中 DataRowIf the command is set to FirstReturnedRecord, then the first returned result is placed in the DataRow.

  5. 如果有输出参数,则将它们放在中 DataRowIf there are output parameters, they are placed in the DataRow.

  6. 引发 OnRowUpdated 事件。The OnRowUpdated event is raised.

  7. 调用 AcceptChangesAcceptChanges is called.

与关联的每个命令 DbDataAdapter 通常都具有与之关联的参数集合。Each command associated with the DbDataAdapter usually has a parameters collection associated with it. 通过 SourceColumn SourceVersion .NET Framework 数据提供程序的类的和属性,将参数映射到当前行 ParameterParameters are mapped to the current row through the SourceColumn and SourceVersion properties of a .NET Framework data provider's Parameter class. SourceColumn 引用 DataTable DbDataAdapter 用于获取当前行的参数值的列。SourceColumn refers to a DataTable column that the DbDataAdapter references to obtain parameter values for the current row.

SourceColumn 在应用了任何表映射之前引用未映射的列名称。SourceColumn refers to the unmapped column name before any table mappings have been applied. 如果 SourceColumn 引用不存在的列,则执行的操作取决于下列值之一 MissingMappingActionIf SourceColumn refers to a nonexistent column, the action taken depends on one of the following MissingMappingAction values.

枚举值Enumeration value 采取的操作Action taken
MissingMappingAction.Passthrough 如果不存在映射,请使用中的源列名称和表名称 DataSetUse the source column names and table names in the DataSet if no mapping is present.
MissingMappingAction.Ignore SystemException生成。A SystemException is generated. 当显式设置映射时,缺少输入参数的映射通常是由错误引起的。When the mappings are explicitly set, a missing mapping for an input parameter is usually the result of an error.
MissingMappingAction.Error SystemException生成。A SystemException is generated.

SourceColumn属性还可用于将输出或输入/输出参数的值映射回 DataSetThe SourceColumn property is also used to map the value for output or input/output parameters back to the DataSet. 如果引用不存在的列,则会生成异常。An exception is generated if it refers to a nonexistent column.

SourceVersion.NET Framework 数据提供程序的类的属性 Parameter 确定是使用列值的原始版本、当前版本还是建议的版本。The SourceVersion property of a .NET Framework data provider's Parameter class determines whether to use the Original, Current, or Proposed version of the column value. 此功能通常用于在 UPDATE 语句的 WHERE 子句中包含原始值,以检查是否存在开放式并发冲突。This capability is often used to include original values in the WHERE clause of an UPDATE statement to check for optimistic concurrency violations.

备注

如果在更新行时出现错误,则会引发异常并中止执行更新。If an error occurs while updating a row, an exception is thrown and execution of the update is discontinued. 若要在遇到错误时继续执行更新操作而不生成异常,请在 ContinueUpdateOnError 调用之前将属性设置为 true UpdateTo continue the update operation without generating exceptions when an error is encountered, set the ContinueUpdateOnError property to true before calling Update. 您还可以在 DataAdapter 事件内每行响应错误 RowUpdatedYou may also respond to errors on a per-row basis within the RowUpdated event of a DataAdapter. 若要继续执行更新操作而不在事件中生成异常 RowUpdated ,请将 Status 的属性设置 RowUpdatedEventArgsContinueTo continue the update operation without generating an exception within the RowUpdated event, set the Status property of the RowUpdatedEventArgs to Continue.

适用于

Update(DataTable)

通过为指定的 DataTable 中的每个已插入、已更新或已删除的行执行相应的 INSERT、UPDATE 或 DELETE 语句来更新数据库中的值。Updates the values in the database by executing the respective INSERT, UPDATE, or DELETE statements for each inserted, updated, or deleted row in the specified DataTable.

public:
 int Update(System::Data::DataTable ^ dataTable);
public int Update (System.Data.DataTable dataTable);
override this.Update : System.Data.DataTable -> int
Public Function Update (dataTable As DataTable) As Integer

参数

dataTable
DataTable

用于更新数据源的 DataTableThe DataTable used to update the data source.

返回

Int32

DataTable 中成功更新的行数。The number of rows successfully updated from the DataTable.

例外

DataSet 无效。The DataSet is invalid.

源表无效。The source table is invalid.

不存在要更新的 DataRowNo DataRow exists to update.

-or- 不存在要更新的 DataTableNo DataTable exists to update.

-or- 不存在要用作源的 DataSetNo DataSet exists to use as a source.

尝试执行 INSERT、UPDATE 或 DELETE 语句,但没有记录受到影响。An attempt to execute an INSERT, UPDATE, or DELETE statement resulted in zero records affected.

示例

下面的示例使用派生类 OleDbDataAdapter 来更新数据源。The following example uses the derived class, OleDbDataAdapter, to update the data source.

public DataTable CreateCmdsAndUpdate(string connectionString,
    string queryString)
{
    using (OleDbConnection connection = new OleDbConnection(connectionString))
    {
        OleDbDataAdapter adapter = new OleDbDataAdapter();
        adapter.SelectCommand = new OleDbCommand(queryString, connection);
        OleDbCommandBuilder builder = new OleDbCommandBuilder(adapter);

        connection.Open();

        DataTable customers = new DataTable();
        adapter.Fill(customers);

        // code to modify data in DataTable here

        adapter.Update(customers);

        return customers;
    }
}

Public Function CreateCmdsAndUpdate(ByVal connectionString As String, _
    ByVal queryString As String) As DataTable

    Using connection As New OleDbConnection(connectionString)
        Dim adapter As New OleDbDataAdapter()
        adapter.SelectCommand = New OleDbCommand(queryString, connection)
        Dim builder As New OleDbCommandBuilder(adapter)

        connection.Open()

        Dim customers As New DataTable()
        adapter.Fill(customers)

        ' Code to modify data in DataTable here 

        adapter.Update(customers)
        Return customers
    End Using
End Function

注解

当应用程序调用 Update 方法时,将 DbDataAdapter 检查 RowState 属性,并根据中配置的索引的顺序,对每个行重复执行所需的 INSERT、UPDATE 或 DELETE 语句 DataSetWhen an application calls the Update method, the DbDataAdapter examines the RowState property, and executes the required INSERT, UPDATE, or DELETE statements iteratively for each row, based on the order of the indexes configured in the DataSet. 例如, Update 可能会执行 DELETE 语句,后跟 INSERT 语句,然后执行另一 delete 语句,因为中的行的顺序 DataTableFor example, Update might execute a DELETE statement, followed by an INSERT statement, and then another DELETE statement, due to the ordering of the rows in the DataTable.

应注意的是,这些语句不作为批处理执行;每一行都单独更新。It should be noted that these statements are not performed as a batch process; each row is updated individually. 应用程序可以 GetChanges 在以下情况下调用方法:例如,必须控制语句类型的序列 (例如,在更新) 之前插入。An application can call the GetChanges method in situations where you must control the sequence of statement types (for example, INSERTs before UPDATEs). 有关详细信息,请参阅 用 Dataadapter 更新数据源For more information, see Updating Data Sources with DataAdapters.

如果尚未指定 INSERT、UPDATE 或 DELETE 语句,则该方法将 Update 生成一个异常。If INSERT, UPDATE, or DELETE statements have not been specified, the Update method generates an exception. 但是, SqlCommandBuilder OleDbCommandBuilder 如果您设置了 SelectCommand .NET Framework 数据提供程序的属性,则可以创建或对象以自动为单表更新生成 SQL 语句。However, you can create a SqlCommandBuilder or OleDbCommandBuilder object to automatically generate SQL statements for single-table updates if you set the SelectCommand property of a .NET Framework data provider. 然后, CommandBuilder 将生成未设置的任何其他 SQL 语句。Then, any additional SQL statements that you do not set are generated by the CommandBuilder. 此代逻辑要求密钥列信息存在于中 DataSetThis generation logic requires key column information to be present in the DataSet. 有关详细信息,请参阅 通过 Commandbuilder 生成命令For more information see Generating Commands with CommandBuilders.

Update 执行更新之前,方法将从第一个映射中列出的表中检索行。The Update method retrieves rows from the table listed in the first mapping before performing an update. Update然后,使用属性的值刷新该行 UpdatedRowSourceThe Update then refreshes the row using the value of the UpdatedRowSource property. 将忽略返回的任何其他行。Any additional rows returned are ignored.

在将任何数据加载回后 DataSet ,将 OnRowUpdated 引发事件,从而允许用户检查已协调的 DataSet 行和该命令返回的任何输出参数。After any data is loaded back into the DataSet, the OnRowUpdated event is raised, allowing the user to inspect the reconciled DataSet row and any output parameters returned by the command. 成功更新行后,将接受对该行所做的更改。After a row updates successfully, the changes to that row are accepted.

使用时 Update ,执行顺序如下所示:When using Update, the order of execution is as follows:

  1. 中的值 DataRow 将被移动到参数值中。The values in the DataRow are moved to the parameter values.

  2. 引发 OnRowUpdating 事件。The OnRowUpdating event is raised.

  3. 命令执行。The command executes.

  4. 如果命令设置为 FirstReturnedRecord ,则将第一个返回的结果放置在中 DataRowIf the command is set to FirstReturnedRecord, then the first returned result is placed in the DataRow.

  5. 如果有输出参数,则将它们放在中 DataRowIf there are output parameters, they are placed in the DataRow.

  6. 引发 OnRowUpdated 事件。The OnRowUpdated event is raised.

  7. 调用 AcceptChangesAcceptChanges is called.

与关联的每个命令 DbDataAdapter 通常都具有与之关联的参数集合。Each command associated with the DbDataAdapter usually has a parameters collection associated with it. 通过 SourceColumn SourceVersion .NET Framework 数据提供程序的类的和属性,将参数映射到当前行 ParameterParameters are mapped to the current row through the SourceColumn and SourceVersion properties of a .NET Framework data provider's Parameter class. SourceColumn 引用 DataTable DbDataAdapter 用于获取当前行的参数值的列。SourceColumn refers to a DataTable column that the DbDataAdapter references to obtain parameter values for the current row.

SourceColumn 在应用了任何表映射之前引用未映射的列名称。SourceColumn refers to the unmapped column name before any table mappings have been applied. 如果 SourceColumn 引用不存在的列,则执行的操作取决于下列值之一 MissingMappingActionIf SourceColumn refers to a nonexistent column, the action taken depends on one of the following MissingMappingAction values.

枚举值Enumeration value 采取的操作Action taken
MissingMappingAction.Passthrough 如果不存在映射,请使用中的源列名称和表名称 DataSetUse the source column names and table names in the DataSet if no mapping is present.
MissingMappingAction.Ignore SystemException生成。A SystemException is generated. 当显式设置映射时,缺少输入参数的映射通常是由错误引起的。When the mappings are explicitly set, a missing mapping for an input parameter is usually the result of an error.
MissingMappingAction.Error SystemException生成。A SystemException is generated.

SourceColumn属性还可用于将输出或输入/输出参数的值映射回 DataSetThe SourceColumn property is also used to map the value for output or input/output parameters back to the DataSet. 如果引用不存在的列,则会生成异常。An exception is generated if it refers to a nonexistent column.

SourceVersion.NET Framework 数据提供程序的类的属性 Parameter 确定是使用列值的原始版本、当前版本还是建议的版本。The SourceVersion property of a .NET Framework data provider's Parameter class determines whether to use the Original, Current, or Proposed version of the column value. 此功能通常用于在 UPDATE 语句的 WHERE 子句中包含原始值,以检查是否存在开放式并发冲突。This capability is often used to include original values in the WHERE clause of an UPDATE statement to check for optimistic concurrency violations.

备注

如果在更新行时出现错误,则会引发异常并中止执行更新。If an error occurs while updating a row, an exception is thrown and execution of the update is discontinued. 若要在遇到错误时继续执行更新操作而不生成异常,请在 ContinueUpdateOnError 调用之前将属性设置为 true UpdateTo continue the update operation without generating exceptions when an error is encountered, set the ContinueUpdateOnError property to true before calling Update. 您还可以在 DataAdapter 事件内每行响应错误 RowUpdatedYou may also respond to errors on a per-row basis within the RowUpdated event of a DataAdapter. 若要继续执行更新操作而不在事件中生成异常 RowUpdated ,请将 Status 的属性设置 RowUpdatedEventArgsContinueTo continue the update operation without generating an exception within the RowUpdated event, set the Status property of the RowUpdatedEventArgs to Continue.

适用于

Update(DataSet)

通过为指定的 DataSet 中的每个已插入、已更新或已删除的行执行相应的 INSERT、UPDATE 或 DELETE 语句来更新数据库中的值。Updates the values in the database by executing the respective INSERT, UPDATE, or DELETE statements for each inserted, updated, or deleted row in the specified DataSet.

public:
 override int Update(System::Data::DataSet ^ dataSet);
public override int Update (System.Data.DataSet dataSet);
override this.Update : System.Data.DataSet -> int
Public Overrides Function Update (dataSet As DataSet) As Integer

参数

dataSet
DataSet

用于更新数据源的 DataSetThe DataSet used to update the data source.

返回

Int32

DataSet 中成功更新的行数。The number of rows successfully updated from the DataSet.

实现

例外

源表无效。The source table is invalid.

尝试执行 INSERT、UPDATE 或 DELETE 语句,但没有记录受到影响。An attempt to execute an INSERT, UPDATE, or DELETE statement resulted in zero records affected.

示例

下面的示例使用派生类 OleDbDataAdapter 来更新数据源。The following example uses the derived class, OleDbDataAdapter, to update the data source.

public DataSet CreateCmdsAndUpdate(string connectionString,
    string queryString)
{
    using (OleDbConnection connection = new OleDbConnection(connectionString))
    {
        OleDbDataAdapter adapter = new OleDbDataAdapter();
        adapter.SelectCommand = new OleDbCommand(queryString, connection);
        OleDbCommandBuilder builder = new OleDbCommandBuilder(adapter);

        connection.Open();

        DataSet customers = new DataSet();
        adapter.Fill(customers);

        //code to modify data in dataset here

        adapter.Update(customers);

        return customers;
    }
}
Public Function CreateCmdsAndUpdate(ByVal connectionString As String, _
    ByVal queryString As String) As DataSet

    Using connection As New OleDbConnection(connectionString)
        Dim adapter As New OleDbDataAdapter()
        adapter.SelectCommand = New OleDbCommand(queryString, connection)
        Dim builder As New OleDbCommandBuilder(adapter)

        connection.Open()

        Dim customers As New DataSet()
        adapter.Fill(customers)

        ' Code to modify data in DataSet here 

        adapter.Update(customers)

        Return customers
    End Using
End Function

注解

当应用程序调用 Update 方法时,将 DbDataAdapter 检查 RowState 属性,并根据中配置的索引的顺序,对每个行重复执行所需的 INSERT、UPDATE 或 DELETE 语句 DataSetWhen an application calls the Update method, the DbDataAdapter examines the RowState property, and executes the required INSERT, UPDATE, or DELETE statements iteratively for each row, based on the order of the indexes configured in the DataSet. 例如, Update 可能会执行 DELETE 语句,后跟 INSERT 语句,然后执行另一 delete 语句,因为中的行的顺序 DataTableFor example, Update might execute a DELETE statement, followed by an INSERT statement, and then another DELETE statement, due to the ordering of the rows in the DataTable.

应注意的是,这些语句不作为批处理执行;每一行都单独更新。It should be noted that these statements are not performed as a batch process; each row is updated individually. 应用程序可以 GetChanges 在以下情况下调用方法:例如,必须控制语句类型的序列 (例如,在更新) 之前插入。An application can call the GetChanges method in situations where you must control the sequence of statement types (for example, INSERTs before UPDATEs). 有关详细信息,请参阅 用 Dataadapter 更新数据源For more information, see Updating Data Sources with DataAdapters.

如果尚未指定 INSERT、UPDATE 或 DELETE 语句,则该方法将 Update 生成一个异常。If INSERT, UPDATE, or DELETE statements have not been specified, the Update method generates an exception. 但是, SqlCommandBuilder OleDbCommandBuilder 如果您设置了 SelectCommand .NET Framework 数据提供程序的属性,则可以创建或对象以自动为单表更新生成 SQL 语句。However, you can create a SqlCommandBuilder or OleDbCommandBuilder object to automatically generate SQL statements for single-table updates if you set the SelectCommand property of a .NET Framework data provider. 然后, CommandBuilder 将生成未设置的任何其他 SQL 语句。Then, any additional SQL statements that you do not set are generated by the CommandBuilder. 此代逻辑要求密钥列信息存在于中 DataSetThis generation logic requires key column information to be present in the DataSet. 有关详细信息,请参阅 通过 Commandbuilder 生成命令For more information see Generating Commands with CommandBuilders.

Update 执行更新之前,方法将从第一个映射中列出的表中检索行。The Update method retrieves rows from the table listed in the first mapping before performing an update. Update然后,使用属性的值刷新该行 UpdatedRowSourceThe Update then refreshes the row using the value of the UpdatedRowSource property. 将忽略返回的任何其他行。Any additional rows returned are ignored.

在将任何数据加载回后 DataSet ,将 OnRowUpdated 引发事件,从而允许用户检查已协调的 DataSet 行和该命令返回的任何输出参数。After any data is loaded back into the DataSet, the OnRowUpdated event is raised, allowing the user to inspect the reconciled DataSet row and any output parameters returned by the command. 成功更新行后,将接受对该行所做的更改。After a row updates successfully, the changes to that row are accepted.

使用时 Update ,执行顺序如下所示:When using Update, the order of execution is as follows:

  1. 中的值 DataRow 将被移动到参数值中。The values in the DataRow are moved to the parameter values.

  2. 引发 OnRowUpdating 事件。The OnRowUpdating event is raised.

  3. 命令执行。The command executes.

  4. 如果命令设置为 FirstReturnedRecord ,则将第一个返回的结果放置在中 DataRowIf the command is set to FirstReturnedRecord, then the first returned result is placed in the DataRow.

  5. 如果有输出参数,则将它们放在中 DataRowIf there are output parameters, they are placed in the DataRow.

  6. 引发 OnRowUpdated 事件。The OnRowUpdated event is raised.

  7. 调用 AcceptChangesAcceptChanges is called.

与关联的每个命令 DbDataAdapter 通常都具有与之关联的参数集合。Each command associated with the DbDataAdapter usually has a parameters collection associated with it. 通过 SourceColumn SourceVersion .NET Framework 数据提供程序的类的和属性,将参数映射到当前行 ParameterParameters are mapped to the current row through the SourceColumn and SourceVersion properties of a .NET Framework data provider's Parameter class. SourceColumn 引用 DataTable DbDataAdapter 用于获取当前行的参数值的列。SourceColumn refers to a DataTable column that the DbDataAdapter references to obtain parameter values for the current row.

SourceColumn 在应用了任何表映射之前引用未映射的列名称。SourceColumn refers to the unmapped column name before any table mappings have been applied. 如果 SourceColumn 引用不存在的列,则执行的操作取决于下列值之一 MissingMappingActionIf SourceColumn refers to a nonexistent column, the action taken depends on one of the following MissingMappingAction values.

枚举值Enumeration value 采取的操作Action taken
MissingMappingAction.Passthrough 如果不存在映射,请使用中的源列名称和表名称 DataSetUse the source column names and table names in the DataSet if no mapping is present.
MissingMappingAction.Ignore SystemException生成。A SystemException is generated. 当显式设置映射时,缺少输入参数的映射通常是由错误引起的。When the mappings are explicitly set, a missing mapping for an input parameter is usually the result of an error.
MissingMappingAction.Error SystemException生成。A SystemException is generated.

SourceColumn属性还可用于将输出或输入/输出参数的值映射回 DataSetThe SourceColumn property is also used to map the value for output or input/output parameters back to the DataSet. 如果引用不存在的列,则会生成异常。An exception is generated if it refers to a nonexistent column.

SourceVersion.NET Framework 数据提供程序的类的属性 Parameter 确定是使用列值的原始版本、当前版本还是建议的版本。The SourceVersion property of a .NET Framework data provider's Parameter class determines whether to use the Original, Current, or Proposed version of the column value. 此功能通常用于在 UPDATE 语句的 WHERE 子句中包含原始值,以检查是否存在开放式并发冲突。This capability is often used to include original values in the WHERE clause of an UPDATE statement to check for optimistic concurrency violations.

备注

如果在更新行时出现错误,则会引发异常并中止执行更新。If an error occurs while updating a row, an exception is thrown and execution of the update is discontinued. 若要在遇到错误时继续执行更新操作而不生成异常,请在 ContinueUpdateOnError 调用之前将属性设置为 true UpdateTo continue the update operation without generating exceptions when an error is encountered, set the ContinueUpdateOnError property to true before calling Update. 您还可以在 DataAdapter 事件内每行响应错误 RowUpdatedYou may also respond to errors on a per-row basis within the RowUpdated event of a DataAdapter. 若要继续执行更新操作而不在事件中生成异常 RowUpdated ,请将 Status 的属性设置 RowUpdatedEventArgsContinueTo continue the update operation without generating an exception within the RowUpdated event, set the Status property of the RowUpdatedEventArgs to Continue.

适用于

Update(DataRow[])

通过为 DataSet 中的指定数组中的每个已插入、已更新或已删除的行执行相应的 INSERT、UPDATE 或 DELETE 语句来更新数据库中的值。Updates the values in the database by executing the respective INSERT, UPDATE, or DELETE statements for each inserted, updated, or deleted row in the specified array in the DataSet.

public:
 int Update(cli::array <System::Data::DataRow ^> ^ dataRows);
public int Update (System.Data.DataRow[] dataRows);
override this.Update : System.Data.DataRow[] -> int
Public Function Update (dataRows As DataRow()) As Integer

参数

dataRows
DataRow[]

用于更新数据源的 DataRow 对象的数组。An array of DataRow objects used to update the data source.

返回

Int32

DataSet 中成功更新的行数。The number of rows successfully updated from the DataSet.

例外

DataSet 无效。The DataSet is invalid.

源表无效。The source table is invalid.

不存在要更新的 DataRowNo DataRow exists to update.

-or- 不存在要更新的 DataTableNo DataTable exists to update.

-or- 不存在要用作源的 DataSetNo DataSet exists to use as a source.

尝试执行 INSERT、UPDATE 或 DELETE 语句,但没有记录受到影响。An attempt to execute an INSERT, UPDATE, or DELETE statement resulted in zero records affected.

示例

下面的示例使用派生类 OleDbDataAdapter 来更新数据源。The following example uses the derived class, OleDbDataAdapter, to update the data source.

public DataSet CreateCmdsAndUpdate(string connectionString,
    string queryString)
{
    using (OleDbConnection connection = new OleDbConnection(connectionString))
    {
        OleDbDataAdapter adapter = new OleDbDataAdapter();
        adapter.SelectCommand = new OleDbCommand(queryString, connection);
        OleDbCommandBuilder builder = new OleDbCommandBuilder(adapter);

        connection.Open();

        DataSet customers = new DataSet();
        adapter.Fill(customers);

        //code to modify data in dataset here

        //Insert new records from DataSet
        DataRow[] rows = customers.Tables[0].Select(
            null, null, DataViewRowState.Added);
        adapter.Update(rows);

        return customers;
    }
}
Public Function CreateCmdsAndUpdate(ByVal connectionString As String, _
    ByVal queryString As String) As DataSet

    Using connection As New OleDbConnection(connectionString)
        Dim adapter As New OleDbDataAdapter()
        adapter.SelectCommand = New OleDbCommand(queryString, connection)
        Dim builder As New OleDbCommandBuilder(adapter)

        connection.Open()

        Dim customers As New DataSet()
        adapter.Fill(customers)

        ' Code to modify data in DataSet here 

        ' Insert new records from DataSet
        Dim rows() As DataRow = customers.Tables(0).Select( _
            Nothing, Nothing, DataViewRowState.Added)
        adapter.Update(rows)

        Return customers
    End Using
End Function

注解

当应用程序调用 Update 方法时,将 DbDataAdapter 检查 RowState 属性,并根据中配置的索引的顺序,对每个行重复执行所需的 INSERT、UPDATE 或 DELETE 语句 DataSetWhen an application calls the Update method, the DbDataAdapter examines the RowState property, and executes the required INSERT, UPDATE, or DELETE statements iteratively for each row, based on the order of the indexes configured in the DataSet. 例如, Update 可能会执行 DELETE 语句,后跟 INSERT 语句,然后执行另一 delete 语句,因为中的行的顺序 DataTableFor example, Update might execute a DELETE statement, followed by an INSERT statement, and then another DELETE statement, due to the ordering of the rows in the DataTable.

应注意的是,这些语句不作为批处理执行;每一行都单独更新。It should be noted that these statements are not performed as a batch process; each row is updated individually. 应用程序可以 GetChanges 在以下情况下调用方法:例如,必须控制语句类型的序列 (例如,在更新) 之前插入。An application can call the GetChanges method in situations where you must control the sequence of statement types (for example, INSERTs before UPDATEs). 有关详细信息,请参阅 用 Dataadapter 更新数据源For more information, see Updating Data Sources with DataAdapters.

如果尚未指定 INSERT、UPDATE 或 DELETE 语句,则该方法将 Update 生成一个异常。If INSERT, UPDATE, or DELETE statements have not been specified, the Update method generates an exception. 但是, SqlCommandBuilder OleDbCommandBuilder 如果您设置了 SelectCommand .NET Framework 数据提供程序的属性,则可以创建或对象以自动为单表更新生成 SQL 语句。However, you can create a SqlCommandBuilder or OleDbCommandBuilder object to automatically generate SQL statements for single-table updates if you set the SelectCommand property of a .NET Framework data provider. 然后, CommandBuilder 将生成未设置的任何其他 SQL 语句。Then, any additional SQL statements that you do not set are generated by the CommandBuilder. 此代逻辑要求密钥列信息存在于中 DataSetThis generation logic requires key column information to be present in the DataSet. 有关详细信息,请参阅 通过 Commandbuilder 生成命令For more information see Generating Commands with CommandBuilders.

Update 执行更新之前,方法将从第一个映射中列出的表中检索行。The Update method retrieves rows from the table listed in the first mapping before performing an update. Update然后,使用属性的值刷新该行 UpdatedRowSourceThe Update then refreshes the row using the value of the UpdatedRowSource property. 将忽略返回的任何其他行。Any additional rows returned are ignored.

在将任何数据加载回后 DataSet ,将 OnRowUpdated 引发事件,从而允许用户检查已协调的 DataSet 行和该命令返回的任何输出参数。After any data is loaded back into the DataSet, the OnRowUpdated event is raised, allowing the user to inspect the reconciled DataSet row and any output parameters returned by the command. 成功更新行后,将接受对该行所做的更改。After a row updates successfully, the changes to that row are accepted.

使用时 Update ,执行顺序如下所示:When using Update, the order of execution is as follows:

  1. 中的值 DataRow 将被移动到参数值中。The values in the DataRow are moved to the parameter values.

  2. 引发 OnRowUpdating 事件。The OnRowUpdating event is raised.

  3. 命令执行。The command executes.

  4. 如果命令设置为,则 FirstReturnedRecord 返回的第一个结果位于中 DataRowIf the command is set to FirstReturnedRecord, the first returned result is placed in the DataRow.

  5. 如果有输出参数,则将它们放在中 DataRowIf there are output parameters, they are placed in the DataRow.

  6. 引发 OnRowUpdated 事件。The OnRowUpdated event is raised.

  7. 调用 AcceptChangesAcceptChanges is called.

与关联的每个命令 DbDataAdapter 通常都具有与之关联的参数集合。Each command associated with the DbDataAdapter usually has a parameters collection associated with it. 通过 SourceColumn SourceVersion .NET Framework 数据提供程序的类的和属性,将参数映射到当前行 ParameterParameters are mapped to the current row through the SourceColumn and SourceVersion properties of a .NET Framework data provider's Parameter class. SourceColumn 引用 DataTable DbDataAdapter 用于获取当前行的参数值的列。SourceColumn refers to a DataTable column that the DbDataAdapter references to obtain parameter values for the current row.

SourceColumn 在应用了任何表映射之前引用未映射的列名称。SourceColumn refers to the unmapped column name before any table mappings have been applied. 如果 SourceColumn 引用不存在的列,则执行的操作取决于下列值之一 MissingMappingActionIf SourceColumn refers to a nonexistent column, the action taken depends on one of the following MissingMappingAction values.

枚举值Enumeration value 采取的操作Action taken
MissingMappingAction.Passthrough 如果不存在映射,请使用中的源列名称和表名称 DataSetUse the source column names and table names in the DataSet if no mapping is present.
MissingMappingAction.Ignore SystemException生成。A SystemException is generated. 当显式设置映射时,缺少输入参数的映射通常是由错误引起的。When the mappings are explicitly set, a missing mapping for an input parameter is usually the result of an error.
MissingMappingAction.Error SystemException生成。A SystemException is generated.

SourceColumn属性还可用于将输出或输入/输出参数的值映射回 DataSetThe SourceColumn property is also used to map the value for output or input/output parameters back to the DataSet. 如果引用不存在的列,则会生成异常。An exception is generated if it refers to a nonexistent column.

SourceVersion.NET Framework 数据提供程序的类的属性 Parameter 确定是使用列值的原始版本、当前版本还是建议的版本。The SourceVersion property of a .NET Framework data provider's Parameter class determines whether to use the Original, Current, or Proposed version of the column value. 此功能通常用于在 UPDATE 语句的 WHERE 子句中包含原始值,以检查是否存在开放式并发冲突。This capability is often used to include original values in the WHERE clause of an UPDATE statement to check for optimistic concurrency violations.

备注

如果在更新行时出现错误,则会引发异常并中止执行更新。If an error occurs while updating a row, an exception is thrown and execution of the update is discontinued. 若要在遇到错误时继续执行更新操作而不生成异常,请在 ContinueUpdateOnError 调用之前将属性设置为 true UpdateTo continue the update operation without generating exceptions when an error is encountered, set the ContinueUpdateOnError property to true before calling Update. 您还可以在 DataAdapter 事件内每行响应错误 RowUpdatedYou may also respond to errors on a per-row basis within the RowUpdated event of a DataAdapter. 若要继续执行更新操作而不在事件中生成异常 RowUpdated ,请将 Status 的属性设置 RowUpdatedEventArgsContinueTo continue the update operation without generating an exception within the RowUpdated event, set the Status property of the RowUpdatedEventArgs to Continue.

适用于