关于微软ADO.NET提供的组件库里的UpdateDataSet()的用法心得

        这个是用了很早的SqlHelper.CS里的函数做例子,但是实际上可以类推到现在微软企业库的Data组件部分。

函数是这样写的
/// <summary>
  /// Executes the respective command for each inserted, updated, or deleted row in the DataSet.
  /// </summary>
  /// <remarks>
  /// e.g.: 
  ///  UpdateDataset(conn, insertCommand, deleteCommand, updateCommand, dataSet, "Order");
  /// </remarks>
  /// <param name="insertCommand">A valid transact-SQL statement or stored procedure to insert new records into the data source</param>
  /// <param name="deleteCommand">A valid transact-SQL statement or stored procedure to delete records from the data source</param>
  /// <param name="updateCommand">A valid transact-SQL statement or stored procedure used to update records in the data source</param>
  /// <param name="dataSet">The DataSet used to update the data source</param>
  /// <param name="tableName">The DataTable used to update the data source.</param>
  public static void UpdateDataset(SqlCommand insertCommand, SqlCommand deleteCommand, SqlCommand updateCommand, DataSet dataSet, string tableName)
  {
   if( insertCommand == null ) throw new ArgumentNullException( "insertCommand" );
   if( deleteCommand == null ) throw new ArgumentNullException( "deleteCommand" );
   if( updateCommand == null ) throw new ArgumentNullException( "updateCommand" );
   if( tableName == null || tableName.Length == 0 ) throw new ArgumentNullException( "tableName" );

   // Create a SqlDataAdapter, and dispose of it after we are done
   using (SqlDataAdapter dataAdapter = new SqlDataAdapter())
   {
    // Set the data adapter commands
    dataAdapter.UpdateCommand = updateCommand;
    dataAdapter.InsertCommand = insertCommand;
    dataAdapter.DeleteCommand = deleteCommand;

    // Update the dataset changes in the data source
    dataAdapter.Update (dataSet, tableName);

    // Commit all the changes made to the DataSet
    dataSet.AcceptChanges();
   }
  }

要注意的几点:
(1)、要把几个Command都要写好了,不然会报错。
(2)、DataTable的TableName一定要定义好,这个自然和你更新的表名相同了。
(3)、传进来的DataSet不要使用了AcceptChanges()这个方法,以此类推DataTable和DataRow。不然更新不了数据库的记录。
(4)、如果数据库是有自增字段的话,且要取出自增值,建议不要使用UpdateDataSet()这个方法,虽然是可以实现。

posted on 2005-12-27 19:19  雾里寻踪  阅读(2851)  评论(6编辑  收藏  举报