萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP.NET 程式設計

ADO.NET DataAdapter 批次更新 (UpdateBatchSize) 完整實作範例

背景

傳統 DataAdapter.Update 逐筆送出 SQL,每筆皆有一次網路往返。ADO.NET 2.0 引入 UpdateBatchSize 可將多筆命令打包成批次執行,大幅提升效能。

完整程式碼範例

protected void btnBatchUpdate_Click(object sender, EventArgs e)
{
    const string connStr = "Data Source=.;Initial Catalog=Northwind;Integrated Security=True";
    
    using (SqlConnection selectConn = new SqlConnection(connStr))
    using (SqlConnection updateConn = new SqlConnection(connStr))
    {
        SqlDataAdapter adapter = new SqlDataAdapter();
        
        // SelectCommand
        adapter.SelectCommand = new SqlCommand("SELECT TOP 500 EmployeeID, Address, City, Region, Country FROM Employees", selectConn);
        
        // UpdateCommand (參數化)
        adapter.UpdateCommand = new SqlCommand(
            "UPDATE Employees SET Address=@Address, City=@City, Region=@Region, Country=@Country WHERE EmployeeID=@EmployeeID", 
            updateConn);
        adapter.UpdateCommand.Parameters.Add("@Address", SqlDbType.NVarChar, 60, "Address");
        adapter.UpdateCommand.Parameters.Add("@City", SqlDbType.NVarChar, 15, "City");
        adapter.UpdateCommand.Parameters.Add("@Region", SqlDbType.NVarChar, 15, "Region");
        adapter.UpdateCommand.Parameters.Add("@Country", SqlDbType.NVarChar, 15, "Country");
        adapter.UpdateCommand.Parameters.Add("@EmployeeID", SqlDbType.Int, 0, "EmployeeID");
        
        // 關鍵:啟用批次更新
        adapter.UpdateBatchSize = 100; // 每 100 筆一批
        adapter.UpdateCommand.UpdatedRowSource = UpdateRowSource.None; // 批次模式必須設為 None 或 OutputParameters
        
        DataTable dt = new DataTable();
        adapter.Fill(dt);
        
        // 模擬修改所有列
        foreach (DataRow row in dt.Rows)
        {
            row["Address"] = "4445 W 77th Street, Suite 140";
            row["City"] = "Edina";
            row["Region"] = "MN";
            row["Country"] = "USA";
        }
        
        // 監聽批次完成事件
        adapter.RowUpdated += (s, args) => 
        {
            lblStatus.Text += $"批次完成至第 {args.RowCount} 筆<br/>";
        };
        
        try
        {
            updateConn.Open();
            int affected = adapter.Update(dt); // 一次送出所有變更
            lblStatus.Text += $"總計更新 {affected} 筆";
        }
        catch (Exception ex)
        {
            lblStatus.Text += $"錯誤: {ex.Message}";
        }
    }
}

關鍵設定說明

屬性建議值說明
UpdateBatchSize10~500 (視網路延遲測試)0=最大批次, 1=停用批次(預設), >1=指定批次筆數
UpdatedRowSourceNone / OutputParameters批次模式不可為 FirstReturnedRecord 或 Both
RowUpdated 事件訂閱每批次完成觸發一次,args.RowCount 為累計筆數

效能測試建議

  • 測試不同 UpdateBatchSize (10, 50, 100, 500) 找出最佳值。
  • 過大批次可能導致交易記憶體壓力、鎖定時間過長、逾時。
  • 搭配 SqlCommand.CommandTimeout 調整。

適用場景

  • 大量資料匯入/同步 (ETL、夜排作業)。
  • 使用者批次編輯 GridView 後一次儲存。
  • 離線資料同步上傳。

現代替代方案

  • SqlBulkCopy:大量插入 (Insert Only) 效能最佳,不支援 Update/Delete。
  • Table-Valued Parameters (TVP):單一預存程序傳入整個 DataTable,伺服器端 MERGE 處理。
  • EF Core / Dapper 批次擴充套件:EFCore.BulkExtensions、Dapper.Contrib 等。
copyright © 萬盛學電腦網 all rights reserved