In many project development scenarios, such as registering a forum user, successful registration is divided into two parts. The first part is to insert a record into the user table first, insert a record to the operation log table. this can be divided into two steps, because the second statement can be executed only after the first insert is successful. in case the first article succeeds, an emergency occurs when the second article is executed, such as a computer crash or a power failure. the system should return the user's status to the status before registration. that is to say, this user registration fails...
To implement the above functions, you need to use SQL transaction processing. The following is a simple example:
Sqlconnection con = new sqlconnection ("Server = (local); database = dB; user id = sa; Pwd = ");
Con. open ();
Sqltransaction ST = con. begintransaction (); // create the Object Transaction named ST through the begintransaction method of sqlconnection
Sqlcommand COM = con. createcommand ();
Com. Transaction = sT; // assign the sqltransaction object to the transaction attribute of the sqlcommand object
Try
{
// Insert registration information to the user table
Com. commandtext = ""; // The insert statement is omitted here. You have to write it yourself ....
Com. executenonquery ();
// Insert data into the log table
Com. commandtext = ""; // The insert statement is also omitted here. You have to write it yourself ....
Com. executenonquery ();
St. Commit (); // submit a transaction
Response. Write ("<SCRIPT> alert ('registration successful! '); Location = 'javascript: history. Go (-1)' </SCRIPT> ");
}
Catch (Exception error)
{
St. rollback (); // rollback
}