Tải bản đầy đủ - 0 (trang)
Part 3: Advanced Database Programming with ADO.NET

Part 3: Advanced Database Programming with ADO.NET

Tải bản đầy đủ - 0trang

ChapterList

Chapter14:AdvancedTransactionControl

Chapter15:IntroducingWebApplications-ASP.NET

Chapter16:UsingSQLServer'sXMLSupport

Chapter17:WebServices



Chapter14:AdvancedTransactionControl



Overview

InChapter3,"IntroductiontotheStructuredQueryLanguage,"yousaw

howyoucangroupSQLstatementsintotransactions.TheseSQL

statementsareconsideredalogicalunitofwork.Oneexampleofthisisa

transferofmoneyfromonebankaccounttoanotherusingtwoUPDATE

statements,onethattakesmoneyoutofoneaccount,andanotherthat

putsthatmoneyintoadifferentaccount.BothUPDATEstatementsmay

beconsideredtobeasingletransactionbecausebothstatementsmust

beeithercommittedorrolledbacktogether,otherwisemoneymightbe

lost.

Today'sdatabasescanhandlemanyusersandprogramsaccessingthe

databaseatthesametime,eachpotentiallyrunningtheirown

transactionsinthedatabase.Theseareknownasconcurrent

transactionsbecausetheyarerunatthesametime.Thedatabase

softwaremustbeabletosatisfytheneedsofalltheseconcurrent

transactions,aswellasmaintaintheintegrityofrowsstoredinthe

databasetables.Youcancontrolthelevelofisolationthatexistsbetween

yourtransactionsandothertransactionsthatmightberunninginthe

database.

InChapter8,"ExecutingDatabaseCommands,"yousawhowtousea

transactionwithaCommandobject.InChapter11,"UsingDataSet

ObjectstoModifyData,"yousawhowtouseatransactionwitha

DataAdapter.Inthischapter,you'lldelveintoadvancedtransaction

controlusingSQLServerandADO.NET.

Featuredinthischapter:

TheSqlTransactionclass

ACIDtransactionproperties

Settingasavepoint

Settingthetransactionisolationlevel



UnderstandingSQLServerlocks



TheSqlTransactionClass

TherearethreeTransactionclasses:SqlTransaction,

OleDbTransaction,andOdbcTransaction.Youusea

Transactionobjecttorepresentadatabasetransaction,andanobject

oftheSqlTransactionclasstorepresentadatabasetransactionina

SQLServerdatabase.Table14.1showssomeoftheSqlTransaction

properties,andTable14.2showssomeoftheSqlTransaction

methods.You'llseetheuseofsomeofthesepropertiesandmethodsin

thischapter.

Table14.1:SqlTransactionPROPERTIES

PROPERTY



TYPE



DESCRIPTION



Connection



SqlConnection Getstheconnectionforthe

transaction.



Getstheisolationlevelforthe

IsolationLevel IsolationLevel transaction(see"Settingthe

TransactionIsolationLevel").

Table14.2:SqlTransactionMETHODS

METHOD



RETURN

DESCRIPTION

TYPE



Commit()



void



Performsacommittopermanentlyrecordthe

SQLstatementsinthetransaction.



Rollback() void



Overloaded.Performsarollbacktoundothe

SQLstatementsinthetransaction.



Save()



Createsasavepointinthetransactionthat

canbeusedtoundoaportionofthat

transaction.Thestringpassedtothismethod

specifiesthesavepointname.Youcanthen

rollbackthetransactiontothatsavepoint

(see"SettingaSavepoint").



void



SettingaSavepoint

Youcansetasavepointanywherewithinatransaction.Thisallowsyou

torollbackanychangesmadetodatabaserowsafteryoursavepoint.

Thismightbeusefulifyouhaveaverylongtransactionbecauseifyou

makeamistakeafteryou'vesetasavepoint,youdon'thavetorollback

thetransactionallthewaytothestart.



SettingaSavepointUsingT-SQL

YousetasavepointinT-SQLusingtheSAVETRANSACTIONstatement,

ortheshorthandversion,SAVETRANS.Thesyntaxforthisstatementis

asfollows:

SAVETRANS[ACTION]{savepointName|@savepointVariable

where

savepointNamespecifiesastringcontainingthenameyou

wanttoassigntoyoursavepoint.

savepointVariablespecifiesaT-SQLvariablethatcontains

yoursavepointname.Yourvariablemustbeofthechar,

varchar,nchar,ornvarchardatatype.

ThefollowingexamplesetsasavepointnamedSaveCustomer:

SAVETRANSACTIONSaveCustomer

Let'slookatacompleteT-SQLexamplescriptthatsetsasavepoint

withinatransaction.Listing14.1showsaT-SQLscriptthatperformsthe

followingsteps:

1. Beginsatransaction.

2. InsertsarowintotheCustomerstablewithaCustomerIDof

J8COM.

3. Setsasavepoint.



4. InsertsarowintotheOrderstablewithaCustomerIDof

J8COM.

5. Performsarollbacktothesavepoint,whichundoestheprevious

insertperformedinstep4,butpreservestheinsertperformedin

step2.

6. Commitsthetransaction,whichcommitstherowinsertedinto

theCustomerstableinstep2.

7. SelectsthenewrowfromtheCustomerstable.

8. AttemptstoselectthefromtheOrderstablethatwasrolled

backinstep5.

9. DeletesthenewrowfromtheCustomerstable.

Listing14.1:SAVEPOINT.SQL

/*

Savepoint.sqlillustrateshowtouseasavepoint

*/

USENorthwind

-step1:beginthetransaction

BEGINTRANSACTION

-step2:insertarowintotheCustomerstable

INSERTINTOCustomers(

CustomerID,CompanyName

)VALUES(

'J8COM','J8Company'

)

-step3:setasavepoint

SAVETRANSACTIONSaveCustomer

-step4:insertarowintotheOrderstable



INSERTINTOOrders(

CustomerID

)VALUES(

'J8COM'

);

-step5:rollbacktothesavepointsetinstep3

ROLLBACKTRANSACTIONSaveCustomer

-step6:committhetransaction

COMMITTRANSACTION

-step7:selectthenewrowfromtheCustomerstable

SELECTCustomerID,CompanyName

FROMCustomers

WHERECustomerID='J8COM'

-step8:attempttoselecttherowfromtheOrderstable

-thatwasrolledbackinstep5

SELECTOrderID,CustomerID

FROMOrders

WHERECustomerID='J8COM'

-step9:deletethenewrowfromtheCustomerstable

DELETEFROMCustomers

WHERECustomerID='J8COM'



ToruntheSavepoint.sqlscriptusingQueryAnalyzer,youselectFile

➣Open,openthescriptfromthesqldirectory,andthenpressF5on

thekeyboardorselectQuery➣Executefromthemenu.Figure14.1

showstheSavepoint.sqlscriptbeingruninQueryAnalyzer.



Figure14.1:Runningthe

Savepoint.sqlscriptinQueryAnalyzer



SettingaSavepointUsingaSqlTransactionObject

YousetasavepointinaSqlTransactionobjectbycallingitsSave()

method,passingastringcontainingthenameyouwishtoassigntoyour

savepoint.AssumeyouhaveaSqlTransactionobjectnamed

mySqlTransaction;thefollowingexamplesetsasavepointnamed

SaveCustomerbycallingtheSave()methodofmySqlTransaction:

mySqlTransaction.Save("SaveCustomer");

Youcanthenrollbackanysubsequentchangesmadetotherowsinthe

databasebycallingtheRollback()methodofmySqlTransaction,

passingthesavepointnametotheRollback()method.Forexample:

mySqlTransaction.Rollback("SaveCustomer");

Let'slookatacompleteC#programthatsetsasavepointwithina

transaction.Listing14.2showsaprogramthatperformsthefollowing

steps:

1. CreatesaSqlTransactionobjectnamed

mySqlTransaction.

2. CreatesaSqlCommandandsetsitsTransactionpropertyto



mySqlTransaction.

3. InsertsarowintotheCustomerstable.

4. SetsasavepointbycallingtheSave()methodof

mySqlTransaction,passingthenameSaveCustomertothe

Save()method.

5. InsertsarowintotheOrderstable.

6. Performsarollbacktothesavepointsetinstep4,whichundoes

thepreviousinsertperformedinstep5,butpreservestheinsert

performedinstep3.

7. DisplaysthenewrowaddedtotheCustomerstable.

8. DeletesthenewrowfromtheCustomerstable.

9. Commitsthetransaction.

Listing14.2:SAVEPOINT.CS



/*

Savepoint.csillustrateshowtosetasavepointinatransact

*/

usingSystem;

usingSystem.Data;

usingSystem.Data.SqlClient;

classSavepoint

{

publicstaticvoidMain()

{

SqlConnectionmySqlConnection=

newSqlConnection(

"server=localhost;database=Northwind;uid=sa;pwd=sa"

);

mySqlConnection.Open();



//step1:createaSqlTransactionobject

SqlTransactionmySqlTransaction=

mySqlConnection.BeginTransaction();



//step2:createaSqlCommandandsetitsTransactionprop

//tomySqlTransaction

SqlCommandmySqlCommand=

mySqlConnection.CreateCommand();

mySqlCommand.Transaction=mySqlTransaction;



//step3:insertarowintotheCustomerstable

Console.WriteLine("InsertingarowintotheCustomerstable

"withaCustomerIDofJ8COM");

mySqlCommand.CommandText=

"INSERTINTOCustomers("+

"CustomerID,CompanyName"+

")VALUES("+

"'J8COM','J8Company'"+

")";

intnumberOfRows=mySqlCommand.ExecuteNonQuery();

Console.WriteLine("Numberofrowsinserted="+numberOfRow

//step4:setasavepointbycallingtheSave()methodof

//mySqlTransaction,passingthename"SaveCustomer"to

//theSave()method

mySqlTransaction.Save("SaveCustomer");



//step5:insertarowintotheOrderstable

Console.WriteLine("InsertingarowintotheOrderstable"+

"withaCustomerIDofJ8COM");

mySqlCommand.CommandText=

"INSERTINTOOrders("+

"CustomerID"+

")VALUES("+

"'J8COM'"+

")";

numberOfRows=mySqlCommand.ExecuteNonQuery();



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Part 3: Advanced Database Programming with ADO.NET

Tải bản đầy đủ ngay(0 tr)

×