When initializing the sqltransaction class, you need to use the begintranscation () method of the sqlconnection class:
Sqltransaction mytran; mytran = myconn. begintransaction ();
This method returns a variable of the sqltransaction type. After the begintransaction () method is called, all SQL statement execution actions based on the data connection object will be considered as part of the transaction mytran. You can also specify the transaction isolation level and transaction name in the parameters of this method, for example:
Sqltransaction mytran;
Mytran = myconn. begintransaction (isolationlevel. readcommitted, "sampletransaction ");
ProgramInstance:
1. SQL Server
Sqlconnection myconn = getconn ();
Myconn. open ();
Sqlcommand mycomm = new sqlcommand ();
Sqltransaction mytran; // create a transaction
Mytran = myconn. begintransaction (); // note that the sqltransaction class has no public constructors.
// From then on, data operations based on the connection are considered as part of the transaction.
Mycomm. Connection = myconn;
Mycomm. Transaction = mytran;
Mycomm. commandtext = "use pubs ";
Mycomm. executenonquery ();
Mycomm. commandtext = "Update roysched set royalty = royalty * 1.10 where title_id like 'pc % '";
Mycomm. executenonquery ();
Mytran. Commit (); // submit the transaction
2. The following example creates an oracleconnection and an oracletransaction.
It also demonstrates how to use the begintransaction, commit, and rollback methods.
Public void runoracletransaction (string myconnstring)
{
Oracleconnection myconnection = new oracleconnection (myconnstring );
Myconnection. open ();
Oraclecommand mycommand = myconnection. createcommand ();
Oracletransaction mytrans;
// Start a local transaction
Mytrans = myconnection. begintransaction (isolationlevel. readcommitted );
// Assign transaction object for a pending local transaction
Mycommand. Transaction = mytrans;
try
{< br> mycommand. commandtext = "insert into dept (deptno, dname, Loc) values (50, 'Technology ', 'Denver')";
mycommand. executenonquery ();
mycommand. commandtype = commandtype. storedprocedure;
mycommand. commandtext = "prc_test";
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 >}