日期:2013-08-17 浏览次数:20392 次
程序实例:
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();
}
}