在初始化SqlTransaction类时,你需要使用SqlConnection类的BeginTranscation()方法:
SqlTransaction myTran; myTran=myConn.BeginTransaction();
该方法返回一个SqlTransaction类型的变量。在调用BeginTransaction()方法以后,所有基于该数据连接对象的SQL语句执行动作都将被认为是事务MyTran的一部分。同时,你也可以在该方法的参数中指定事务隔离级别和事务名称,如:
SqlTransaction myTran;
myTran=myConn.BeginTransaction(IsolationLevel.ReadCommitted,"SampleTransaction");
程序实例:
1. SQL SERVER
SqlConnection myConn=GetConn();
myConn.Open();
SqlCommand myComm=new SqlCommand();
SqlTransaction myTran; //创建一个事务
myTran=myConn.BeginTransaction(); //注意,SqlTransaction类无公开的构造函数
//从此开始,基于该连接的数据操作都被认为是事务的一部分
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(); //提交事务
2.下面的示例创建一个 OracleConnection 和一个 OracleTransaction。
它还演示了如何使用 BeginTransaction、Commit 和 Rollback 方法。
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 (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.");
}
catch(Exception e)
{
myTrans.Rollback();
Console.WriteLine(e.ToString());
Console.WriteLine("Neither record was written to database.");
}
finally
{
myConnection.Close();
}
}