萬盛學電腦網

 萬盛學電腦網 >> 網絡編程 >> 編程語言綜合 >> ADO.NET批量更新操作

ADO.NET批量更新操作

   批量更新操作

  .在上一個版本的ADO.NET當中,SqlDataAdapterde的Update方法將會為 DataSet當中的每一行調用一次更新操作

  .在ADO.NET2.0中,您可以設置UpdateBatchSize屬性,在單步中執行多個更新

  .這樣,可以提高數據更新的效率

  .UpdataBatchSize的默認值為1,使得默認的更新行為與以前版本的ADO.NET一致。

  代碼經驗

  public Form1()

  {

  conn = new SqlConnection(ConfigurationManager.ConnectionStrings["AWConnectionString"].ConnectionString);

  dAdapt = new SqlDataAdapter("SELECT ProductID, Name, ListPrice FROM Production.Product", conn);

  InitializeComponent();

  }

  SqlConnection conn;

  SqlDataAdapter dAdapt;

  DataSet dSet = new DataSet();

  StringBuilder logString = new StringBuilder("");

  private void batchUpdateForm_Load(System.Object sender, System.EventArgs e)

  {

  dAdapt.RowUpdating += new System.Data.SqlClient.SqlRowUpdatingEventHandler(OnRowUpdating);

  dAdapt.RowUpdated += new System.Data.SqlClient.SqlRowUpdatedEventHandler(OnRowUpdated);

  }

  private void getDataButton_Click(System.Object sender, System.EventArgs e)

  {

  dAdapt.Fill(dSet, "Product");

  productGrid.DataSource = dSet.Tables["Product"];

  }

  private void updateDataButton_Click(System.Object sender, System.EventArgs e)

  {

  SqlCommandBuilder cb = new SqlCommandBuilder(dAdapt);

  logString.Remove(0, logString.Length);

  // Enable batching by setting batch size != 1.

  dAdapt.UpdateBatchSize = int.Parse(batchSizeTextBox.Text);

  // Execute the update.

  dAdapt.Update(dSet.Tables["Product"]);

  MessageBox.Show(logString.ToString());

  }

  //handler for the RowUpdating event

  public void OnRowUpdating(object sender, SqlRowUpdatingEventArgs e)

  {

  logString.AppendLine("Starting row update");

  }

  // handler for RowUpdated event

  public void OnRowUpdated(object sender, SqlRowUpdatedEventArgs e)

  {

  logString.AppendLine("Completed row update");

  }

copyright © 萬盛學電腦網 all rights reserved