數(shù)據(jù)庫(kù)事務(wù)
數(shù)據(jù)庫(kù)事務(wù)是其他事務(wù)模型的基礎(chǔ),本文討論的事務(wù)都是基于數(shù)據(jù)庫(kù)事務(wù)實(shí)現(xiàn)的,他們僅是隱藏了處理事務(wù)的復(fù)雜的或者容器專有的代碼。當(dāng)一個(gè)事務(wù)創(chuàng)建時(shí)不同數(shù)據(jù)庫(kù)系統(tǒng)都有自己的規(guī)則。缺省地,sql server工作在自動(dòng)提交的模式下,每個(gè)語(yǔ)句執(zhí)行完后會(huì)立即提交,與此對(duì)照的是oracle需要你包含一個(gè)提交語(yǔ)句。但是當(dāng)一個(gè)語(yǔ)句通過(guò)oledb執(zhí)行時(shí),它執(zhí)行完后一個(gè)提交動(dòng)作會(huì)被附加上去。為了使下面的例子適用于oracle,你需要去掉begin transation和commit transation兩個(gè)語(yǔ)句,因?yàn)檫@兩個(gè)語(yǔ)句會(huì)當(dāng)作一個(gè)單獨(dú)的事務(wù)來(lái)運(yùn)行。
優(yōu)勢(shì)
l 所有的事務(wù)邏輯包含在一個(gè)單獨(dú)的調(diào)用中
l 擁有運(yùn)行一個(gè)事務(wù)的最佳性能
l 獨(dú)立于應(yīng)用程序
限制
l 事務(wù)上下文僅存在于數(shù)據(jù)庫(kù)調(diào)用中
l 數(shù)據(jù)庫(kù)代碼與數(shù)據(jù)庫(kù)系統(tǒng)有關(guān)
例子:
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事務(wù)
創(chuàng)建一個(gè)ado.net事務(wù)是很簡(jiǎn)單的,僅僅是標(biāo)準(zhǔn)代碼的一個(gè)小的擴(kuò)展。只要你知道如何使用ado.net來(lái)訪問(wèn)數(shù)據(jù)庫(kù),那就差不多知道了。區(qū)別僅僅是你需要把代碼放到一個(gè)事務(wù)上下文中。
還是原來(lái)的ado.net類庫(kù)引用,在實(shí)現(xiàn)事務(wù)的類里面引入system.data和system.data.sqlclient類庫(kù),為了執(zhí)行一個(gè)事務(wù),你需要?jiǎng)?chuàng)建一個(gè)sqltransation對(duì)象,可以調(diào)用你的sqlconnection對(duì)象begintransation()方法來(lái)創(chuàng)建它,一旦你把sqltransation對(duì)象存為本地變量,你就可以把它賦給你的sqlcommand對(duì)象的事務(wù)屬性,或者把它作為構(gòu)造器的一個(gè)參數(shù)來(lái)創(chuàng)建sqlcommand。在執(zhí)行sqlcommand動(dòng)作之前,你必須調(diào)用begintransaction()方法,然后賦給sqlcommand事務(wù)屬性。
一單事務(wù)開始了,你就可以執(zhí)行任何次數(shù)的sqlcommand動(dòng)作,只要它是屬于同一個(gè)事務(wù)和連接。最后你可以調(diào)用sqltransation的commit()方法來(lái)提交事務(wù)。
ado.net事務(wù)實(shí)際上是把事務(wù)上下文傳遞到數(shù)據(jù)庫(kù)層,如果事務(wù)中發(fā)生一個(gè)錯(cuò)誤,數(shù)據(jù)庫(kù)會(huì)自動(dòng)回滾。在你的錯(cuò)誤處理代碼中,每次調(diào)用rollback()方法之前檢查事務(wù)對(duì)象是否存在是一種良好的習(xí)慣。這樣的一個(gè)例子是當(dāng)一個(gè)死鎖發(fā)生的同時(shí),數(shù)據(jù)庫(kù)正在執(zhí)行自動(dòng)回滾。
優(yōu)勢(shì):
l 簡(jiǎn)單性
l 和數(shù)據(jù)庫(kù)事務(wù)差不多的快
l 事務(wù)可以跨越多個(gè)數(shù)據(jù)庫(kù)訪問(wèn)
l 獨(dú)立于數(shù)據(jù)庫(kù),不同數(shù)據(jù)庫(kù)的專有代碼被隱藏了
限制:
事務(wù)執(zhí)行在數(shù)據(jù)庫(kù)連接層上,所以你需要在事務(wù)過(guò)程中手動(dòng)的維護(hù)一個(gè)連接
例子:
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事務(wù)
asp.net事務(wù)可以說(shuō)是在.net平臺(tái)上事務(wù)實(shí)現(xiàn)方式中最簡(jiǎn)單的一種,你僅僅需要加一行代碼。在aspx的頁(yè)面聲明中加一個(gè)額外的屬性,即是事務(wù)屬性,它可以有 如下的值:disabled (缺省), notsupported, supported, required 和 requiresnew,這些設(shè)置和com+以及企業(yè)級(jí)服務(wù)中的設(shè)置一樣,典型地如果你想在頁(yè)面上下文中運(yùn)行事務(wù),那么要設(shè)置為required。如果頁(yè)面中包含有用戶控件,那么這些控件也會(huì)包含到事務(wù)中,事務(wù)會(huì)存在于頁(yè)面的每個(gè)地方。
優(yōu)勢(shì):
l 實(shí)現(xiàn)簡(jiǎn)單,不需要額外的編碼
限制:
l 頁(yè)面的所有代碼都是同一個(gè)事務(wù),這樣的事務(wù)可能會(huì)很大,而也許我們需要的是分開的、小的事務(wù)
l 事務(wù)實(shí)在web層
例子:
aspx page
<%@ page transaction="required" language="c#" codebehind="aspnet_transaction.aspx.cs"
inherits="transtest.aspnet_transaction" autoeventwireup="false"%>
<html>
<head>
<title>asp.net transaction</title>
</head>
<body ms_positioning="gridlayout">
<form id="aspnet_transaction" method="post" runat="server">
</form>
</body>
</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事務(wù)的代碼基本一樣,我們只是移除了對(duì)sqltransation對(duì)象的引用。這些事務(wù)被aspx頁(yè)面的聲明transaction="required"所代替。在事務(wù)統(tǒng)計(jì)中,當(dāng)頁(yè)面執(zhí)行后,事務(wù)數(shù)目會(huì)增加,一個(gè)語(yǔ)句失敗后,所有的語(yǔ)句將會(huì)回滾,你會(huì)看到事務(wù)被取消了。
圖7:asp.net事務(wù)的統(tǒng)計(jì)
新聞熱點(diǎn)
疑難解答
圖片精選