Ado. NET transaction processing

Source: Internet
Author: User

Four steps to perform an ADO transaction

Take SqlTransaction object as an example to introduce:

1) Call the BeginTransaction () method of the SqlConnection object to create a SqlTransaction object that marks the start of the transaction.

2) assigns the created SqlTransaction object to the transaction property of the SqlCommand to be executed.

3) Call the appropriate method to execute the SqlCommand command.

4) Call SqlTransaction's commit () method to complete the transaction, or call the rollback () method to abort the transaction.

Note: Before you call the BeginTransaction () method to open a database connection, an exception will occur before the transaction is started.

Value of text box input
string txtname = TextBox1.Text;
Connecting to a database
String str = "Data source=.; Initial catalog=myschool;uid=sa;password= ";
SqlConnection con = new SqlConnection (str);

SQL statements

String sql = "INSERT into Grade values ('" + TextBox1.Text + "')";
SqlCommand cmd = new SqlCommand (Sql,con);
Con. Open ();
After the connection is opened, gets a transaction object
SqlTransaction tr= con. BeginTransaction ();
Bind the already constructed transaction object with the Transction property of CMD
Cmd. Transaction = TR;
int Count=cmd. ExecuteNonQuery ();
if (Count > 0)
{
MessageBox.Show ("add success");
Tr.commit (); Commit a transaction
}
Else
{
Tr. Rollback (); Rolling back a transaction
}
Con. Close ();

Ado. NET transaction processing

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.