Use Dataadpater to automatically batch update data in a dataset to a database

Source: Internet
Author: User


[WebMethod (Description = "Update Service provides a method that synchronizes the Dateset with the modified data to the local database, successfully returns the updated number of rows, and the failure returns-1.) "), SoapHeader (" CurrentUser ")]
public int Update (DataSet ds)
{
if (! ValidateUser (Currentuser.username, Currentuser.userpass))
{
return-1;
}
Else
{
int res = 0;

using (SqlConnection sqlconn = new SqlConnection ("Data source=.;i Nitial catalog=xxxx; User Id=sa; Password=sa "))
{
Sqlconn. Open ();

////using enhanced read/write lock transactions
SqlTransaction tran = sqlconn. BeginTransaction (isolationlevel.readcommitted);
Try
{

foreach (DataRow Dr in DS. Tables[0]. Rows)
{
All rows are set to modify state
Dr. SetModified ();
}


Locating the target table for adapter
SqlCommand cmd = new SqlCommand (string. Format ("select * from {0} where 1=0", ds. Tables[0]. TableName), sqlconn, Tran);

SqlDataAdapter da = new SqlDataAdapter (cmd);


SqlCommandBuilder Sqlcmdbuilder = new SqlCommandBuilder (DA);
Da. AcceptChangesDuringUpdate = false;


SqlCommand updatecmd = new SqlCommand (string. Format ("UPDATE [{0}] SET [Name] = @Name WHERE ([ID] = @ID)", DS. Tables[0]. TableName));
Do not modify the source DataTable
Updatecmd. UpdatedRowSource = Updaterowsource.none;
Da. UpdateCommand = Updatecmd;


Da. UPDATECOMMAND.PARAMETERS.ADD ("@Name", SqlDbType.NVarChar, "Name");
Da. UPDATECOMMAND.PARAMETERS.ADD ("@ID", SqlDbType.Int, 4, DS. Tables[0]. Columns[0]. ColumnName);



Da. UpdateBatchSize = 10000;


res = da. Update (ds. Tables[0]);


Ds. AcceptChanges ();
Tran.commit ();

Sqlconn. Close ();

}
Catch
{

Tran. Rollback ();
return-1;
}


}
return res;
}


}

Note: If you do not specify DataAdapter UpdateCommand, DataAdapter CommandBuilder automatically constructs the default update command

Use Dataadpater to automatically batch update data in a dataset to a database

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.