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