用Microsoft.net实现数据库事务(二)

数据库事务

数据库事务是其他事务模型的基础,本文讨论的事务都是基于数据库事务实现的,他们仅是隐藏了处理事务的复杂的或者容器专有的代码。当一个事务创建时不同数据库系统都有自己的规则。缺省地, SQL Server 工作在自动提交的模式下,每个语句执行完后会立即提交,与此对照的是 Oracle 需要你包含一个提交语句。但是当一个语句通过 OLEDB 执行时,它执行完后一个提交动作会被附加上去。为了使下面的例子适用于 Oracle ,你需要去掉 begin transation 和 commit transation 两个语句,因为这两个语句会当作一个单独的事务来运行。

优势

l 所有的事务逻辑包含在一个单独的调用中

l 拥有运行一个事务的最佳性能

l 独立于应用程序

限制

l 事务上下文仅存在于数据库调用中

l 数据库代码与数据库系统有关

例子:

CREATE PROCEDURE up_purchaseItem (

@customerId as int,

@itemId int,

@itemqty int)

AS

DECLARE @orderid int

BEGIN TRANSACTION

-- Update the inventory based on purchase

UPDATE inventory

SET qtyinstock = qtyinstock - @itemqty

WHERE inventory.productid = @itemid;

IF @@Error != 0 GOTO ERROR_HANDLER

-- Insert the order into the database

INSERT INTO orders

VALUES (@customerId, @itemId, @itemqty, getdate());

IF @@Error != 0 GOTO ERROR_HANDLER

SET @orderid = @@IDENTITY

COMMIT TRANSACTION

RETURN @orderid

ERROR_HANDLER:

ROLLBACK TRANSACTION

SET NOCOUNT OFF

RETURN 0

GO

ADO.NET 事务

创建一个 ADO.NET 事务是很简单的,仅仅是标准代码的一个小的扩展。只要你知道如何使用 ADO.NET 来访问数据库,那就差不多知道了。区别仅仅是你需要把代码放到一个事务上下文中。

还是原来的 ADO.NET 类库引用,在实现事务的类里面引入 System.Data 和 System.Data.SqlClient 类库,为了执行一个事务,你需要创建一个 SqlTransation 对象,可以调用你的 SqlConnection 对象 BeginTransation() 方法来创建它,一旦你把 SqlTransation 对象存为本地变量,你就可以把它赋给你的 SqlCommand 对象的事务属性,或者把它作为构造器的一个参数来创建 SqlCommand 。在执行 SqlCommand 动作之前,你必须调用 BeginTransaction() 方法,然后赋给 SqlCommand 事务属性。

一单事务开始了,你就可以执行任何次数的 SqlCommand 动作,只要它是属于同一个事务和连接。最后你可以调用 SqlTransation 的 Commit() 方法来提交事务。

ADO.NET 事务实际上是把事务上下文传递到数据库层,如果事务中发生一个错误,数据库会自动回滚。在你的错误处理代码中,每次调用 Rollback() 方法之前检查事务对象是否存在是一种良好的习惯。这样的一个例子是当一个死锁发生的同时,数据库正在执行自动回滚。

优势:

l 简单性

l 和数据库事务差不多的快

l 事务可以跨越多个数据库访问

l 独立于数据库,不同数据库的专有代码被隐藏了

限制:

事务执行在数据库连接层上,所以你需要在事务过程中手动的维护一个连接

例子:

public int purchaseitem(int customerId, int itemId, int itemQty)

{

SqlConnection con = null;

SqlTransaction tx = null;

int orderId = 0;

try

{

con = new SqlConnection("Data Source=localhost; user

Id=sa;password=;Initial Catalog=trans_db;");

con.Open();

tx = con.BeginTransaction(IsolationLevel.Serializable);

String updatesqltext = "UPDATE inventory SET qtyinstock

= qtyinstock - " + itemQty.ToString()

+ " WHERE inventory.productid = " + itemId.ToString();

SqlCommand cmd = new SqlCommand(updatesqltext, con, tx);

cmd.ExecuteNonQuery();

// String is 2 SQL statements: the first is the insert,

the second selects the identity column

String insertsqltext = "INSERT INTO orders VALUES

(" + customerId.ToString() + "," + itemId.ToString()

+ "," + itemQty.ToString() + " , getdate() ); SELECT @@IDENTITY";

cmd.CommandText = insertsqltext;

// Retrieve the order id from the identity column

orderId = Convert.ToInt32(cmd.ExecuteScalar());

cmd.Dispose();

tx.Commit();

}

catch (SqlException sqlex)

{

// Specific catch for deadlock

if (sqlex.Number != 1205)

{

tx.Rollback();

}

orderId = 0;

throw(sqlex);

}

catch (Exception ex)

{

tx.Rollback();

orderId = 0;

throw (ex);

}

finally

{

tx.Dispose();

con.Close();

}

}

ASP.NET 事务

ASP.NET 事务可以说是在 .Net 平台上事务实现方式中最简单的一种,你仅仅需要加一行代码。在 ASPX 的页面声明中加一个额外的属性,即是事务属性,它可以有 如下的值: Disabled ( 缺省 ), NotSupported, Supported, Required 和 RequiresNew ,这些设置和 COM+ 以及企业级服务中的设置一样,典型地如果你想在页面上下文中运行事务,那么要设置为 Required 。如果页面中包含有用户控件,那么这些控件也会包含到事务中,事务会存在于页面的每个地方。

优势:

l 实现简单,不需要额外的编码

限制:

l 页面的所有代码都是同一个事务,这样的事务可能会很大,而也许我们需要的是分开的、小的事务

l 事务实在 Web 层

例子:

ASPX page

1@ Page Transaction="Required" language="c#" Codebehind="ASPNET_Transaction.aspx.cs" 
2
3Inherits="TransTest.ASPNET_Transaction"  AutoEventWireup="false"
1<html>
2<head>
3<title>ASP.NET Transaction</title>
4</head>
5<body ms_positioning="GridLayout">
6<form id="ASPNET_Transaction" method="post" runat="server">
7</form>
8</body>
9</html>

ASPX Code behind page

using System;

using System.Collections;

using System.ComponentModel;

using System.Data;

using System.Data.SqlClient;

using System.Drawing;

using System.Web;

using System.Web.SessionState;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.HtmlControls;

namespace TransTest

{

/// Summary description for ASPNET_Transaction.

public class ASPNET_Transaction : System.Web.UI.Page

{

public int purchaseitem(int customerId, int itemId, int itemQty)

{

SqlConnection con = null;

int orderId = 0;

try

{

con = new SqlConnection("Data Source=localhost; user

Id=sa;password=;Initial Catalog=trans_db;");

con.Open();

String updatesqltext = "UPDATE inventory SET qtyinstock = qtyinstock

- " + itemQty.ToString() + " WHERE inventory.productid = " +

itemId.ToString();

SqlCommand cmd = new SqlCommand(updatesqltext, con);

cmd.ExecuteNonQuery();

String insertsqltext = "INSERT INTO orders VALUES

(" + customerId.ToString() + "," + itemId.ToString() + ","

+ itemQty.ToString() + " , getdate() ); SELECT @@IDENTITY";

cmd.CommandText = insertsqltext;

orderId = Convert.ToInt32(cmd.ExecuteScalar());

cmd.Dispose();

}

catch (Exception ex)

{

orderId = 0;

throw (ex);

}

finally

{

con.Close();

}

return orderId;

}

private void Page_Load(object sender, System.EventArgs e)

{

int orderid = purchaseitem(1, 1, 10);

Response.Write(orderid);

}

#region Web Form Designer generated code

}

}

注意到这些和 ADO.NET 事务的代码基本一样,我们只是移除了对 SqlTransation 对象的引用。这些事务被 ASPX 页面的声明 Transaction="Required" 所代替。在事务统计中,当页面执行后,事务数目会增加,一个语句失败后,所有的语句将会回滚,你会看到事务被取消了。

** **

图 7 : ASP.Net 事务的统计


Published At
Categories with Web编程
Tagged with
comments powered by Disqus