首页 > 开发 > 综合 > 正文

使用 DataAdapter 执行批量更新

2024-07-21 02:29:09
字体:
来源:转载
供稿:网友

   摘自msdn:

  在以前版本的 ado.net 中,使用 dataset 中的更改来更新数据库时,dataadapter 的 update 方法每次更新数据库的一行。因为该方法循环访问指定 datatable 中的行,所以,会检查每个 datarow,确定是否已修改。如果该行已修改,将根据该行的 rowstate 属性值调用相应的 updatecommand、insertcommand 或 deletecommand。每一次行更新都涉及网络与数据库之间的双向数据传输。

  在 ado.net 2.0 中,dataadapter 公开了 updatebatchsize 属性。将 updatebatchsize 设置为正整数值将使对数据库的更新以指定大小的批次进行发送。例如,如果将 updatebatchsize 设置为 10,会将 10 个独立的语句组合在一起并作为一批提交。将 updatebatchsize 设置为 0 将导致 dataadapter 使用服务器可以处理的最大批次的大小。如果将其设置为 1,则禁用批量更新,因为此时每次发送一行。

  执行非常大的批次可能会降低性能。因此,在实现应用程序之前,应测试最佳的批次大小设置。

  使用 updatebatchsize 属性

  启用了批量更新后,dataadapter 的 updatecommand、insertcommand 和 deletecommand 的 updatedrowsource 属性值应设置为 none 或 outputparameters。在执行批量更新时,命令的 firstreturnedrecord 或 both 的 updatedrowsource 属性值无效。

  下面的过程演示如何使用 updatebatchsize 属性。该过程采用两个参数,一个 dataset 对象,其中包含代表 production.productcategory 表中的 productcategoryid 和 name 字段的列,一个代表批次大小的整数(批次中的行数)。该代码创建一个新的 sqldataadapter 对象,设置其 updatecommand、insertcommand 和 deletecommand 属性。该代码假定 dataset 对象已修改了行。它设置 updatebatchsize 属性并执行更新。

protected void btnupdateaddress_click(object sender, eventargs e)
    {
        sqldataadapter empadapter = new sqldataadapter();
        datatable empdt = new datatable();
        sqlconnection dbconselect = new sqlconnection();
        sqlconnection dbconupdate = new sqlconnection();
        sqlcommand selectcommand = new sqlcommand();
        sqlcommand updatecommand = new sqlcommand();

        // using different connection objects for select and updates from the
        // northwind database.
        dbconselect.connectionstring =
          configurationmanager.connectionstrings["dsn_northwind"].connectionstring;
        dbconupdate.connectionstring =
          configurationmanager.connectionstrings["dsn_northwind"].connectionstring;

        // reading all records from the employees table
        selectcommand.commandtext = "select top 500 * from employees";
        selectcommand.commandtype = commandtype.text;
        selectcommand.connection = dbconselect;

        updatecommand.commandtext = " update employees set [email protected], " +
                                    "[email protected], [email protected], [email protected]";

        updatecommand.commandtype = commandtype.text;
        updatecommand.connection = dbconupdate;

        sqlparameter addressparam;
        addressparam = new sqlparameter("@address",
           sqldbtype.varchar, 15, "address");

        sqlparameter cityparam;
        cityparam = new sqlparameter("@city", sqldbtype.varchar, 15, "city");

        sqlparameter regionparam;
        regionparam = new sqlparameter("@region", sqldbtype.varchar, 15, "region");

        sqlparameter countryparam;
        countryparam = new sqlparameter("@country",
           sqldbtype.varchar, 15, "country");

        updatecommand.parameters.add(addressparam);
        updatecommand.parameters.add(cityparam);
        updatecommand.parameters.add(regionparam);
        updatecommand.parameters.add(countryparam);

        // setting up data adapter with the select and update commands
        // the select command will be used to retrieve all employee
        // information from the northwind database and the update command
        // will be used to save changes back to the database
        empadapter.selectcommand = selectcommand;
        empadapter.updatecommand = updatecommand;

        empadapter.fill(empdt);

        dbconselect.close();

        // looping through all employee records and assigning them the new
        // address
        foreach (datarow dr in empdt.rows)
        {
            dr["address"] = "4445 w 77th street, suite 140";
            dr["city"] = "edina";
            dr["region"] = "minnesota";
            dr["country"] = "usa";
        }

        // adding an event handler to listen to the rowupdated event.
        // this event will will fire after each batch is executed
        empadapter.rowupdated +=  new sqlrowupdatedeventhandler(onrowupdated);

        lblcounter.text = "";

        empadapter.updatebatchsize = 100;

        // it is important to set this property for batch processing of
        // updated records since batch updates are incapable of
        // updating the source with changes from the database
        updatecommand.updatedrowsource = updaterowsource.none;

        try
        {
            dbconupdate.open();
            empadapter.update(empdt);
        }
        catch (exception ex)
        {
            lblcounter.text += ex.message + "<br>";
        }
        finally
        {
            if (dbconupdate.state == connectionstate.open)
            {
                dbconupdate.close();
            }
        }
    }

    private void onrowupdated(object sender, sqlrowupdatedeventargs args)
    {
        lblcounter.text += "batch is processed till row number = " +
           args.rowcount.tostring() + "<br>";
    }

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表