• 关于微软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()这个方法,虽然是可以实现。

  • 相关阅读:
    Jmeter-跨线程组传参
    HTTP请求方法:GET和POST
    Java之数组的遍历、最大值、最小值、、总和、平均值、数组的复制,反转,查找(线性查找、二分法查找)
    Java数组
    Java代码题2
    Java程序流程控制
    Java代码题
    JAVA基本语法
    Java语言特性与基础
    jmeter接口测试带有token的请求
  • 原文地址:https://www.cnblogs.com/zsxfbj/p/306049.html
Copyright © 2020-2023  润新知