Data | Database 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 type sqltransaction. After the BeginTransaction () method is invoked, all SQL statement execution actions based on the data connection object are considered to be part of the transaction Mytran. You can also specify transaction isolation levels and transaction names in the parameters of the method, such as:
SqlTransaction Mytran;
Mytran=myconn.begintransaction (isolationlevel.readcommitted, "sampletransaction");
Program instance:
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 exposed constructors
From this point on, data operations based on the connection are considered to be 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 (); Commit a transaction
2. The following example creates a OracleConnection and a 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
{
myCommand.CommandText = "INSERT into Dept (DeptNo, dname, Loc) VALUES (, ' TECHNOLOGY ', ' DENVER ')";
Mycommand.executenonquery ();
Mycommand.commandtype= CommandType.StoredProcedure;
mycommand.commandtext= "Prc_test";
Mycommand.executenonquery ();
Mytrans.commit ();
Console.WriteLine ("Both records are written to database.");
}
catch (Exception e)
{
Mytrans.rollback ();
Console.WriteLine (E.tostring ());
Console.WriteLine ("Neither record is written to database.");
}
Finally
{
Myconnection.close ();
}
}