t;%@ Import Namespace="System.Web.Configuration" %>
<script runat="server">
void btnSave_Click(object sender, EventArgs e)
{
CommittableTransaction trans = new CommittableTransaction();
try
{
string connectionString = WebConfigurationManager.ConnectionStrings
["Mydatabase"].ConnectionString;
using (SqlConnection connection = new SqlConnection(connectionString))
{
string sql = "Insert into Production.ProductCategory(Name," +
"rowguid, ModifiedDate) Values(@Name, @rowguid, @ModifiedDate)";
// 打开连接,在事务范围中登记此连接
connection.Open();
SqlCommand command = new SqlCommand(sql, connection);
command.CommandType = CommandType.Text;
SqlParameter nameParam =
new SqlParameter("@Name", SqlDbType.NVarChar, 50);
nameParam.Value = txtCategoryName.Text;
command.Parameters.Add(nameParam);
SqlParameter guidParam = new SqlParameter("@rowguid",
SqlDbType.UniqueIdentifier);
guidParam.Value = System.Guid.NewGuid();
command.Parameters.Add(guidParam);
SqlParameter modifieDateParam = new SqlParameter("@ModifiedDate",
SqlDbType.DateTime);
modifieDateParam.Value = System.DateTime.Now;
command.Parameters.Add(modifieDateParam);
//在当前事务的范围中登记事务
connection.EnlistTransaction(trans);
command.ExecuteNonQuery();
// 如果每一个执行都成功,则提交事务
trans.Commit();
}
lblResult.Text = "Category is written successfully";
}
catch (Exception ex)
{
// 如果出现异常,则回滚事务
trans.Rollback();
lblResult.Text = "Exception is : " + ex.Message;
}
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Using Explicit Transactions using CommittableTransaction</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="lblCategoryName" runat="server"
Text="Category Name:" Width="179px"></asp:Label>
<asp:TextBox ID="txtCategoryName" runat="server" />
<asp:Button ID="btnSave" runat="server" Text="Save" Width="92px"
OnClick="btnSave_Click" />
<br /><br />
<asp:Label ID="lblResult" runat="server" Font-Bold="true"
Font-Size="Small" />
</div>
</form>
</body>
</html>
在这种方法中,需要调用SqlConnection对象的EnlistTransaction()方法(传递CommittableTransaction对象作为参数),以便将SqlConnection对象与CommittableTransaction对象关联起来。一旦完成这个工作,然后就可以通过调用CommittableTransaction对象的Commit()和Rollback()方法,显式提交或者回滚事务。正如能够想象的,不推荐使用这种手动方法,因为当发生不同类型的异常时,可能会遇到一些无法回滚事务的风险。
使用TransactionScope类
正如名称所暗示,TransactionScope类用于限定事务代码块,其具有一些明显优点,例如范围与应用程序对象模型无关,同时提供了一个简单直观的编程模型等等。在该类的构造函数内部,TransactionScope对象创建了一个事务(.NET 2.0中默认时轻量级事务管理器),同时将该事务设置给Transaction类的Current属性。由于TransactionScope是可释放对象,所以事务将调用Dispose()方法释放该对象:
using(Tran