Perform multiple operations on the database using C # Transaction Processing

Source: Internet
Author: User
There are three database operation statements a B C, and multiple operations are performed using C # transaction processing. If any statement has a problem, all statements are not executed.

 

 

C # code

Sqlcommand sqlcmd = new sqlcommand ();
Sqlcmd. Connection = sqlcnn;
Sqlcmd. Transaction = sqlcnn. begintransaction (); // complete the preparatory work for transaction processing.

try
{
// write user-registered data to the database
string sqlcmd1 = "insert into user_login (user_id, user_pwd) values ('"+ user_id +"', '"+ user_pwd +"') ";
string sqlcmd2 =" insert into user_data_basic values ('"+ user_id + "', '"+ user_name +"', '"+ user_sex +"', "+ user_age_year +", "+ user_age_month +", "+ user_age_day + ",'','', '','', '')";
string sqlcmd3 = "insert into user_data_comunication (user_id) values ('" + user_id + "')";
string sql1_4 = "insert into user_data_like (user_id) values ('" + user_id + "')";
string sql1_5 = "insert into user_data_schooldata (user_id) values ('"+ user_id +"') ";
// string sql1_6 =" insert into user_data_status (user_id, user_status_date) values ('"+ user_id + "', '"+ system. datetime. now + "')";

string [] sqlstringlist = {sqlcmd1, sqlcmd2, sqlcmd3, sql1_4, sql1_5};
for (INT I = 0; I {< br> string sqlstr = sqlstringlist [I]. tostring ();
If (sqlstr. trim (). length> 1)
{< br> sqlcmd. commandtext = sqlstr;
sqlcmd. executenonquery ();
}< BR >}< br> sqlcmd. transaction. commit ();
}< br> catch (exception exe)
{< br> sqlcmd. transaction. rollback ();
flag = false;
// This. finalcheck. TEXT = exe. message. tostring ();
}< br> finally
{< br> // close the database
sqlcnn. close ();
}

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.