Using system;
Using system. Collections. Generic;
Using system. componentmodel;
Using system. Data;
Using system. drawing;
Using system. LINQ;
Using system. text;
Using system. Windows. forms;
Using system. Data. sqlclient;
/* A transaction is a group of operations that are treated as a unit. They are either all successful or all failed during execution.
For example, transfer
Two levels of transactions
Database-level transactions
Ado. net transaction
If you need to update the database multiple times in an operation, you must use transactions.
Sqltransaction mytransaction
= Myconnection. begintransaction ();
Try
{...
Mycommand = new oledbcommand (Response STR, myconnection, mytransaction );
...
Mytransaction. Commit ();
}
Catch (exception es)
{
Mytransaction. rollback ();
}
*/
Namespace transaction
{
Public partial class form1: Form
{
Public form1 ()
{
Initializecomponent ();
}
Private void button#click (Object sender, eventargs E)
{
String connectionstring = system. configuration. configurationmanager. etettings ["connectionstring"];
Sqlconnection myconn = new sqlconnection (connectionstring );
Try
{
Myconn. open ();
Sqltransaction mytransaction = myconn. begintransaction (); // create a transaction
Try
{
String destination STR = "update account set money = money-100 Where id = '1 '";
Sqlcommand mycmd = new sqlcommand (writable STR, myconn, mytransaction );
Mycmd. executenonquery ();
Throw new exception (); // if an exception is thrown, it will be caught directly by the catch.
String character str2 = "update account set money = money + 100 Where id = '2 '";
Sqlcommand mycmd1 = new sqlcommand (cmdstr2, myconn, mytransaction );
Myapps1.executenonquery ();
Mytransaction. Commit (); // only after this sentence is executed can the data in the database be changed.
}
Catch (exception ee)
{
Mytransaction. rollback (); // roll back
MessageBox. Show ("Transfer failed, rolling back! ");
}
Myconn. Close ();
}
Catch (exception ex)
{
MessageBox. Show ("database connection failed! ");
}
}
}
}