In ADO. net, you can use the connection and transaction objects to control transactions. To execute a transaction, perform the following operations:
Call the begintransaction method of the connection object to mark the start of the transaction. Begintransaction returns a reference to transaction. Keep this reference so that it is assigned to the command registered in the transaction.
Assign the transaction object to the transaction attribute of the command to be executed. If you execute command on the connection through the active transaction object, but the transaction object has not been assigned the transaction attribute to the command, an exception is thrown.
Run the required command.
Call the commit method of the transaction object to complete the transaction, or call the rollback method to cancel the transaction.
BelowCodeMicrosoft? SQL Server? To demonstrate the transaction logic.
Sqlconnection myconnection = new sqlconnection ("Data Source = localhost; initial catalog = northwind; Integrated Security = sspi ;");
Myconnection. open ();
// Start a transaction
Sqltransaction mytrans = myconnection. begintransaction ();
// create a command for the transaction
sqlcommand mycommand = new sqlcommand ();
mycommand. connection = myconnection;
mycommand. transaction = mytrans;
try
{< br> mycommand. commandtext = "insert into region (regionid, regiondescription) values (100," Description ")";
mycommand. executenonquery ();
mycommand. commandtext = "insert into region (regionid, regiondescription) values (101," Description ")";
mycommand. executenonquery ();
mytrans. commit ();
console. writeline ("both records are written to database. ");
}< br> catch (exception e)
{< br> mytrans. rollback ();
console. writeline (E. tostring ();
console. writeline ("neither record was written to database. ");
}< br> finally
{< br> myconnection. close ();
}< br>