Tải bản đầy đủ (.pdf) (1,729 trang)

OReilly ADO dot NET 3 5 cookbook 2nd edition mar 2008 ISBN 0596101406

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (16.33 MB, 1,729 trang )

ADO.NET3.5Cookbook,2ndEdition
byBillHamilton
Publisher:O'Reilly
PubDate:March15,2008
PrintISBN-13:978-0-596-10140-4
Pages:980
TableofContents|Index

Overview
ThisguideisstrikinglydifferentfromotherbooksonMicrosoft
ADO.NET.Ratherthanloadyoudownwiththeory,thenew
editionofADO.NET3.5Cookbookgivesyoumorethan200
codingsolutionsandbestpracticesforrealproblemsyou're
likelytofacewiththistechnologyusingVisualStudio2008and
the.NET3.5platform.Organizedtohelpyoufindthetopicand
specificrecipeyouneedquicklyandeasily,thisbookismore
thanjustahandycompilationofcut-and-pasteC#code.
ADO.NET3.5Cookbookalsooffersclearexplanationsofhow
andwhyeachcodesolutionworks,andwarnsyouofpotential
pitfallssoyoucanlearntoadaptthebook'sproblem-solving
techniquestodifferentsituations.Thiscollectionoftimesaving
recipescoversvitaltopicsincluding:
Connectingtodata
Retrievingandmanagingdata
Transformingandanalyzingdata
Modifyingdata
Bindingdatato.NETuserinterfaces
Optimizing.NETdataaccess
Enumeratingandmaintainingdatabaseobjects



Maintainingdatabaseintegrity
IdealforADO.NETprogrammersatalllevels,fromtherelatively
inexperiencedtothemostsophisticated,thisneweditioncovers
thesignificant3.5upgrade,includingnewprogrammingtools
suchasLINQ.ADO.NET3.5Cookbookoffersapainlesswayfor
thoseofyouwhoprefertolearnbydoingwhenitcomesto
expandingyourskillsandproductivity.


ADO.NET3.5Cookbook,2ndEdition
byBillHamilton
Publisher:O'Reilly
PubDate:March15,2008
PrintISBN-13:978-0-596-10140-4
Pages:980
TableofContents|Index

ADO.NET3.5Cookbook™,SecondEdition
Preface
Chapter1.ConnectingtoData
Recipe1.0.Introduction
Recipe1.1.StoringConnectionStrings
Recipe1.2.BuildingaConnectionString
Recipe1.3.ConnectingtoSQLServer
Recipe1.4.ConnectingtoaNamedInstanceofSQLServer
Recipe1.5.ConnectingtoSQLServerUsinganIPAddress
Recipe1.6.ConnectingtoSQLServerUsingIntegrated
SecurityfromASP.NET
Recipe1.7.ConnectingtoanOracleDatabase
Recipe1.8.ConnectingtoanOLEDBDataSource

Recipe1.9.ConnectingtoanODBCDataSource
Recipe1.10.ConnectingtoaMicrosoftAccessDatabase
Recipe1.11.ConnectingtoaPassword-ProtectedMicrosoft
AccessDatabase
Recipe1.12.ConnectingtoaMicrosoftAccessDatabase
fromASP.NET
Recipe1.13.ConnectingtoaMicrosoftExcelWorkbook
Recipe1.14.ConnectingtoaTextFile
Recipe1.15.ChangingtheDatabaseforanOpenConnection
Recipe1.16.SettingConnectionPoolingOptions
Recipe1.17.TakingAdvantageofConnectionPooling


Recipe1.18.UsingTransactionswithPooledConnections
Recipe1.19.DisplayingaConnectionPropertyDialogBox
Recipe1.20.DisplayingtheDataLinkPropertiesDialogBox
Recipe1.21.MonitoringConnections
Chapter2.WorkingwithDisconnectedDataObjects
Recipe2.0.Introduction
Recipe2.1.CreatingaDataColumnandAddingIttoa
DataTable
Recipe2.2.CreatingaDataTableandAddingIttoaDataSet
Recipe2.3.MappingTableandColumnNamesBetweena
DataSourceandDataSet
Recipe2.4.Mapping.NETDataProviderDataTypesto.NET
FrameworkDataTypes
Recipe2.5.AddingaCalculatedColumntoaDataTable
Recipe2.6.CreatingaUniqueConstraint
Recipe2.7.CreatingSingle-andMulti-ColumnPrimaryKeys
Recipe2.8.CreatinganAutoincrementingPrimaryKey

Recipe2.9.CreatingaForeignKeyConstraint
Recipe2.10.CreatingaDataRelation
Recipe2.11.BuildingaDataSetProgrammatically
Recipe2.12.AddingaColumntoaChildDataTableThat
DisplaysDatafromtheParentTable
Recipe2.13.AddingaColumntoaParentDataTableThat
AggregatesaChildTable'sColumnValues
Recipe2.14.ConvertingBetweenaDataTableanda
DataRowArray
Recipe2.15.AccessingDataValuesinaDataRowArray
Recipe2.16.CreatingaStronglyTypedDataSet
Recipe2.17.ControllingtheNamesUsedinaStronglyTyped
DataSet
Recipe2.18.ReplacingNullValuesinaStronglyTyped
DataSet


Chapter3.QueryingandRetrievingData
Recipe3.0.Introduction
Recipe3.1.ExecutingaQueryThatDoesNotReturna
ResultSet
Recipe3.2.ExecutingaQueryThatReturnsaSingleValue
Recipe3.3.RetrievingaResultSetStreamUsinga
DataReader
Recipe3.4.AccessingDataValuesinaDataReader
Recipe3.5.RetrievingaResultSetUsingaDataTableora
DataSet
Recipe3.6.AccessingDataValuesinaDataTableorDataSet
Recipe3.7.WorkingwithDatainaStronglyTypedDataSet
Recipe3.8.WorkingwithParent-ChildRelationsina

StronglyTypedDataSet
Recipe3.9.UsingaDataViewwithaStronglyTypedDataSet
Recipe3.10.TestingWhetheraQueryReturnsanEmpty
ResultSet
Recipe3.11.CountingRecordsMeetingCriteria
Recipe3.12.DeterminingtheNumberofRecordsReturned
inaDataReader
Recipe3.13.ExecutingaQueryThatReturnsMultipleResult
Sets
Recipe3.14.RetrievingSchemaandConstraintsfora
DataSet
Recipe3.15.RetrievingHierarchicalData
Recipe3.16.NavigatingBetweenParentandChildTablesin
anUntypedDataSet
Recipe3.17.ExecutingaParameterizedQuery
Recipe3.18.RetrievingDataUsingaSQLServerStored
Procedure
Recipe3.19.RetrievingMultipleResultSetsUsingtheOracle
Provider
Recipe3.20.PassingaNullValuetoaQueryParameter


Recipe3.21.UsingTable-ValuedTypesAsParameters
Recipe3.22.RetrievingaReturnValuefromaStored
Procedure
Recipe3.23.RetrievingaStoredProcedureOutput
Parameter
Recipe3.24.RaisingandHandlingStoredProcedureErrors
Recipe3.25.ExecutingaSQLServerScalar-ValuedFunction
Recipe3.26.ExecutingaSQLServerTable-ValuedFunction

Recipe3.27.QueryingaDataSetUsingLINQ
Recipe3.28.QueryingaSQLServerDatabaseUsingLINQ
Recipe3.29.RetrievingDatafromaTextFile
Recipe3.30.RetrievingDatafromaMicrosoftExcel
Workbook
Recipe3.31.QueryingDataAsynchronouslywithMessage
Queuing
Chapter4.SearchingandAnalyzingData
Recipe4.0.Introduction
Recipe4.1.DeterminingtheDifferencesinDataBetween
TwoDataSetObjects
Recipe4.2.CombiningDatafromHeterogeneousData
Sources
Recipe4.3.FilteringRowsinaDataTableorDataView
Recipe4.4.FindingRowsinaDataTableorDataView
Recipe4.5.FilteringandSortingDatainaDataTable
Recipe4.6.FilteringNullFieldValuesinaDataTable
Recipe4.7.AccessingDeletedRowsinaDataTable
Recipe4.8.SelectingtheTopNRowsinaDataTable
Recipe4.9.ExecutingQueriesThatUseCOMPUTEBY
Recipe4.10.UsingtheShapeLanguagetoRetrieve
HierarchicalData
Recipe4.11.RetrievingaRandomSampleofRecords
Recipe4.12.UsingaCommonTableExpression(CTE)
Recipe4.13.ExecutingaRecursiveQuery


Recipe4.14.RetrievingaRankedResultSet
Recipe4.15.RetrievingaPivotandUnpivotTable
Recipe4.16.InvokingaFunctionforEachRowinaResult

Set
Chapter5.AddingandModifyingData
Recipe5.0.Introduction
Recipe5.1.UsingAutoincrementingColumnsWithout
CausingConflicts
Recipe5.2.GettinganIdentityColumnValuefromSQL
Server
Recipe5.3.GettinganAutoNumberValuefromMicrosoft
Access
Recipe5.4.GettingaSequenceValuefromOracle
Recipe5.5.ModifyingDatainaMicrosoftExcelWorkbook
Recipe5.6.ModifyingDatainaTextFile
Recipe5.7.RetrievingUpdateErrors
Recipe5.8.AddingParent/ChildRowswithAutoincrementing
Keys
Recipe5.9.AddingRecordswithaGUIDPrimaryKey
Recipe5.10.InsertingMultipleRowsintoaDatabaseTable
UsingT-SQLRowConstructors
Recipe5.11.UpdatingaDataSourcewithDatafroma
DifferentDataSource
Recipe5.12.UpdatingaPrimaryKeyValue
Recipe5.13.GettingStoredProcedureParameter
InformationatRuntime
Recipe5.14.UpdatingaDataSetwithaMany-to-Many
Relationship
Recipe5.15.UpdatingDataAsynchronouslyUsingMessage
Queuing
Recipe5.16.ControllingEdits,Deletions,orAdditionsto
DatawithaDataView
Recipe5.17.OvercomingKeywordConflictsWhenUsinga



CommandBuilder
Recipe5.18.CapturingChangestoDatainaSQLServer
Database
Chapter6.CopyingandTransferringData
Recipe6.0.Introduction
Recipe6.1.CopyingRowsfromOneDataTabletoAnother
Recipe6.2.CopyingTablesfromOneDataSettoAnother
Recipe6.3.ConvertingaDataReadertoaDataTable
Recipe6.4.ConvertingaDataReadertoaDataSet
Recipe6.5.ConvertingaDataTabletoaDataReader
Recipe6.6.ConvertingaDataSettoaDataReader
Recipe6.7.SerializingData
Recipe6.8.DeserializingData
Recipe6.9.MergingDatainTwoDataSetObjects
Recipe6.10.MergingDatainTwoDatabaseTables
Recipe6.11.EncryptingaDataSet
Recipe6.12.SecuringLoginCredentials
Recipe6.13.ExportingtheResultsofaQueryAsaString
Recipe6.14.ExportingtheResultsofaQuerytoanArray
Recipe6.15.LoadinganADORecordsetintoaDataSet
Recipe6.16.ConvertingaDataSettoanADORecordset
Chapter7.MaintainingDatabaseIntegrity
Recipe7.0.Introduction
Recipe7.1.UsingDistributedTransactions
Recipe7.2.UsingManualTransactions
Recipe7.3.NestingManualTransactionswiththeSQL
Server.NETDataProvider
Recipe7.4.UsingADO.NETandSQLServerDBMS

TransactionsTogether
Recipe7.5.UsingaTransactionwithaDataAdapter
Recipe7.6.AvoidingReferentialIntegrityProblemswhen
UpdatingDatainRelatedTables


Recipe7.7.EnforcingBusinessRuleswithColumn
Expressions
Recipe7.8.RetrievingConstraintsfromaSQLServer
Database
Recipe7.9.CheckingforConcurrencyViolations
Recipe7.10.ResolvingDataConflicts
Recipe7.11.UsingTransactionIsolationLevelstoProtect
Data
Recipe7.12.SpecifyingLockingHintsinaSQLServer
Database
Chapter8.ProgrammaticallyWorkingwithDatain.NET
WindowsandWebFormsUserInterfaces
Recipe8.0.Introduction
Recipe8.1.LoadingDataintoandBindingaFieldtoaWeb
FormsControl
Recipe8.2.BindingDatatoaWebFormsControl
Recipe8.3.BindingDatatoaWebFormsDetailsView
Control
Recipe8.4.BindingDatatoaWebFormsRepeaterControl
Recipe8.5.BindingDatatoaWebFormsDataListControl
Recipe8.6.BindingDatatoaWebFormsGridViewControl
Recipe8.7.ModifyingandUpdatingDatainaWebForms
GridViewControl
Recipe8.8.BindingDatatoaWebFormsFormViewControl

Recipe8.9.SynchronizingMaster-DetailDatainaWeb
FormsApplication
Recipe8.10.DisplayinganImagefromaDatabaseinaWeb
FormsControl
Recipe8.11.LocalizingClient-SideDatainaWebForms
Application
Recipe8.12.LoadingDataintoandBindingaFieldtoa
WindowsFormsControl
Recipe8.13.BindingDatatoaWindowsFormsControl


Recipe8.14.BindingDatatoaWindowsForms
DataGridViewControl
Recipe8.15.ModifyingandUpdatingDatainaWindows
FormsDataGridViewControl
Recipe8.16.UsingWindowsFormsBindingNavigatorand
BindingSourceControls
Recipe8.17.SynchronizingMaster-DetailDatainaWindows
FormsApplication
Recipe8.18.DisplayinganImagefromaDatabaseina
WindowsFormsControl
Recipe8.19.BindingaGroupofRadioButtonstoaWindows
FormsDataField
Recipe8.20.SearchingaWindowsFormsDataGridView
Control
Chapter9.WorkingwithXMLData
Recipe9.0.Introduction
Recipe9.1.UsinganXMLFiletoSaveandLoadaDataSetor
aDataTable
Recipe9.2.UsingXSDSchemaFilestoSaveandLoada

DataSetStructure
Recipe9.3.FormattingColumnValuesWhenSavingDataAs
XML
Recipe9.4.CreatinganXMLFileThatShowsChangesMade
toaDataSet
Recipe9.5.SynchronizingaDataSetandanXMLDocument
Recipe9.6.StoringandRetrievingXMLwithaNon-XMLData
TypeColumn
Recipe9.7.WorkingwithaSQLServerXMLDataType
Column
Recipe9.8.UsinganXPathQuerytoRetrieveData
Recipe9.9.ReadingXMLDataDirectlyfromSQLServer
Recipe9.10.TransformingaDataSetUsingXSLT
Recipe9.11.FillingaDataSetUsinganXMLTemplateQuery


Recipe9.12.UsingOpenXMLtoUpdateMultipleChangesto
SQLServer
Chapter10.Optimizing.NETDataAccess
Recipe10.0.Introduction
Recipe10.1.ExecutingMultipleCommandsonaSingle
Connection
Recipe10.2.ExecutingaSQLStatementAsynchronously
Recipe10.3.ExecutingSimultaneousSQLStatements
Asynchronously
Recipe10.4.CreatingaDataReaderAsynchronously
Recipe10.5.FillingaDataSetAsynchronously
Recipe10.6.CancelinganAsynchronousQuery
Recipe10.7.CachingData
Recipe10.8.ImprovingPagingPerformance

Recipe10.9.XMLBulkLoadingwithSQLServer
Recipe10.10.BulkCopyingwithSQLServer
Recipe10.11.ImprovingDataReaderPerformancewith
TypedAccessors
Recipe10.12.ImprovingDataReaderPerformancewith
ColumnOrdinals
Recipe10.13.DebuggingaSQLServerStoredProcedure
Recipe10.14.ImprovingPerformanceWhileFillinga
DataSet
Recipe10.15.ReadingandWritingLarge-ValueDatawith
SQLServer
Recipe10.16.ReadingandWritingaSQLServerUserDefinedType(UDT)
Recipe10.17.ReadingandWritingOracleLargeData
Recipe10.18.PerformingBatchUpdateswithaDataAdapter
Recipe10.19.AutomaticallyRefreshingaDataTable
Periodically
Recipe10.20.AutomaticallyRefreshingaDataTableWhen
UnderlyingDataChanges


Recipe10.21.RetrievingSQLServerRuntimeStatistics
Recipe10.22.WritingProvider-andDatabase-Independent
Code
Chapter11.EnumeratingandMaintainingDatabaseObjects
Recipe11.0.Introduction
Recipe11.1.EnumeratingSQLServers
Recipe11.2.RetrievingDatabaseMetadata
Recipe11.3.RetrievingDatabaseSchemaInformationfrom
SQLServer
Recipe11.4.RetrievingColumnDefaultValuesfromSQL

Server
Recipe11.5.DeterminingtheLengthofColumnsinaSQL
ServerTable
Recipe11.6.RetrievingaSQLServerQueryPlan
Recipe11.7.RetrievingSQLServerColumnMetadata
WithoutReturningData
Recipe11.8.CreatingaNewSQLServerDatabase
Recipe11.9.AddingaTabletoaSQLServerDatabase
Recipe11.10.CreatingaDatabaseTablefromaDataTable
Schema
Recipe11.11.CreatingDataSetRelationshipsfromSQL
ServerRelationships
Recipe11.12.CreatingaNewMicrosoftAccessDatabase
Recipe11.13.ListingTablesinanAccessDatabase
Recipe11.14.Enumerating.NETDataProviders
Recipe11.15.EnumeratingOLEDBProviders
Recipe11.16.EnumeratingODBCDrivers
Recipe11.17.ChangingaSQLServerUserPassword
Chapter12.SQLServerCLRIntegration
Recipe12.0.Introduction
Recipe12.1.CreatingaStoredProcedure
Recipe12.2.CreatingaScalar-ValuedFunction


Recipe12.3.CreatingaTable-ValuedFunction
Recipe12.4.CreatinganAggregateFunction
Recipe12.5.CreatingaUser-DefinedType
Recipe12.6.CreatingaDMLTrigger
Recipe12.7.CreatingaDDLTrigger
AppendixA.What'sNewinADO.NETSinceVersion1.0

RecipeA.1.ADO.NET2.0
RecipeA.2.ADO.NET3.5
Colophon
Index


ADO.NET3.5Cookbook™,SecondEdition
byBillHamilton
Copyright©2008O'ReillyMedia,Inc.Allrightsreserved.
PrintedintheUnitedStatesofAmerica.
PublishedbyO'ReillyMedia,Inc.,1005GravensteinHighway
North,Sebastopol,CA95472.
O'Reillybooksmaybepurchasedforeducational,business,or
salespromotionaluse.Onlineeditionsarealsoavailablefor
mosttitles(safari.oreilly.com).Formoreinformation,contact
ourcorporate/institutionalsalesdepartment:(800)998-9938or

Editor:

JohnOsborn Indexer:

EllenTroutman
Zaig

Production
Editor:

Rachel
Monaghan


Cover
Designer:

Karen
Montgomery

Copyeditor:

Colleen
Gorman

Interior
Designer:

DavidFutato

Proofreader:

Nancy
Reinhardt

Illustrator:

JessamynRead

PrintingHistory:



September2003:


FirstEdition.

March2008:

SecondEdition.

NutshellHandbook,theNutshellHandbooklogo,andthe
O'ReillylogoareregisteredtrademarksofO'ReillyMedia,Inc.
TheCookbookseriesdesignations,ADO.NET3.5Cookbook,the


imageofawhitespoonbill,andrelatedtradedressare
trademarksofO'ReillyMedia,Inc.
Manyofthedesignationsusedbymanufacturersandsellersto
distinguishtheirproductsareclaimedastrademarks.Where
thosedesignationsappearinthisbook,andO'ReillyMedia,Inc.
wasawareofatrademarkclaim,thedesignationshavebeen
printedincapsorinitialcaps.
Whileeveryprecautionhasbeentakeninthepreparationofthis
book,thepublisherandauthorassumenoresponsibilityfor
errorsoromissions,orfordamagesresultingfromtheuseof
theinformationcontainedherein.
ISBN:978-0-596-10140-4
[C]


Preface
MicrosoftADO.NET3.5isthelatestdataaccesstechnologyfrom
Microsoft.ADO.NETisacollectionofclassesthatarepartofthe

.NETFramework,andisdesignedtoprovideconsistentaccess
todatainlooselycoupledn-tierapplicationarchitecturessuch
aswebservices.ADO.NETcanbeusedtoaccessavarietyof
datasourcesincludingdatabasessuchasMicrosoftSQLServer,
Oracle,andMicrosoftAccess,aswellasXML,OLEDB,and
ODBCdatasources.
ADO.NETseparatesdataaccessfrommanipulation.Connected
classesavailablein.NETdataprovidersconnecttoadata
source,executecommands,andretrieveresults.Disconnected
classesletyouaccessandmanipulatedataofflineandlater
synchronizechangeswiththeunderlyingdatasource.XML
supportistightlyintegratedwithADO.NET,allowingyoutoload,
access,andmanipulatedatausingXMLaswellasthe
disconnectedclassessimultaneously.
ADO.NETisverydifferentfromitspredecessorADO.Withthe
increasingpopularityof.NETandADO.NET,therearemany
questionsfromdevelopersabouthowtosolvespecificproblems
andhowtoimplementsolutionsmostefficiently.Thisbookisa
referencecontainingsolutionsandtechniquesthatmakeusing
ADO.NETeasierandmoreproductive.Youmayhavealready
encounteredsomeoftheseproblems;othersyoumaynever
see.Someofthesolutionsareresponsestoproblemsthathave
beenpostedinvariousdiscussiongroups,whileothersarereal
problemsencounteredwhilebuildingapplications.
Thisbookisorganizedintochapters,witheachchapter
containingsolutions(statedasrecipes)toaspecificproblem
category.Eachrecipeconsistsofasinglequestionandits
solutionfollowedbyadiscussion.Thequestion-answerformat
providescompletesolutionstoproblems,makingiteasytoread
anduse.Everyrecipecontainsacomplete,documentedcode

sampleshowingyouhowtosolvethespecificproblem,aswell


asadiscussionofhowtheunderlyingtechnologyworksanda
discussionofalternatives,limitations,andotherconsiderations
whenappropriate.

P2.1.What'sNewintheSecondEdition
Alothaschangedsincethefirsteditionofthisbook.ADO.NET
hashadtwosignificantreleases—versions2.0and3.5.SQL
ServerhasalsohadtwomajorreleaseswithSQLServer2005
andSQLServer2008.The.NETFrameworkhashadthree
majorreleaseswithversions2.0,3.0,and3.5.AndVisual
StudiohashadtwomajorreleaseswithVisualStudio2005and
2008.Thisbookisupdatedforthelatestversionofallofthese
technologies.
Thisbookisasignificantrevisionfromthefirstedition.In
additiontotheobviousreasonforrevisingthisbookinorderto
covertechnologychanges,Iwantedtoimproveonthefirst
editioninanumberofimportantways.First,Iwantedtomake
thebookeasiertouseandmoreaccessible.Inadditionto
updatingandaddingrecipestocoverneworchanged
technologyandtools,therecipeshavebeenreorganizedand
newrecipesaddedtofillingapsthatIandotherssaw.A
numberofnewrecipesintheearlychaptersaddresscore
conceptsindepth.ThesecondchangethatImadewasto
rewritemostofthesolutionsasWindowsconsoleapplications.
WhiletheWindowsFormssolutionsinthefirsteditionhada
certainelegance,Ifeltthattheadditionalcoderequiredandthe
complexityinbothbuildingandpresentingthesolutions

distractedfromthecoreobjectiveofdemonstratingsolutionsto
ADO.NETproblems.Italsomadeitdifficulttoshowoutputfrom
thesolutions.WindowsandWebFormssolutionsarepresented
asnecessary,especiallywhendemonstratinghowtouse
ADO.NETcontrols.I'vealsorewrittencodetofocusonand
highlightthesolutionandtoprogrammaticallyexplorekey
conceptsratherthanrelyingonthereaderrunningand
interactingwiththesolution.Third,Iwantedtomakethebook
moreusableasastandaloneresource—thatis,withoutloading


codesamples.Sampleoutputhasbeenincludedforeach
solution.Andfinally,Iwantedtomakethebookmoreuseful
andreadableinmanysmallways—I'veclarifiedandexpanded
(andinsomecasesreduced)explanations,increased
consistencyinthewaysolutionsarepresented,andofcourse
fixedafewerrorsalongtheway.

P2.2.WhoThisBookIsFor
Youdon'thavetobeanexperienced.NETdevelopertousethis
book;itisdesignedforusersofalllevels.Thisbookprovides
solutionstoproblemsthatdevelopersfaceeveryday.Reference
ortutorialbookscanteachgeneralconceptsbutdonotusually
providehelpsolvingreal-worldproblems.Thisbookteachesby
example,thenaturalwayformostpeopletolearn.
Althoughsomeofthesamplesinthisbookuseadvanced
techniques,theproblemstheyaddressarefrequentlyfacedby
developerswithalllevelsofexperience.Thecodesamplesare
allcomplete,wellcommented,andthoroughlyexplainedtohelp
youapplythemandsolveyourownproblemsquickly,easily,

andefficiently.
Atthesametime,youwillunderstandexactlyhowandwhythe
solutionworks,therequirements,trade-offs,anddrawbacks.
Thisbookisdesignedtomoveyouupthelearningcurve
quickly.
Thisbookpresentscodetogetherwithoutputsothatyoucan
usebookwithoutloadingtheactualcode.Codegenerated
automaticallybyVisualStudioisnotshown.Youdon'tneedto
retypethecodeinthisbooksinceitisavailableinbothC#and
VisualBasicontheO'Reillywebsite
(T-SQLand
PL/SQLcodeisalsoavailablefordownload.

P2.3.WhatYouNeedtoUseThisBook
Torunthesamplesinthisbook,youwillneedacomputer


runningWindows2000orlater.TheWebFormssolutions
requireMicrosoftInternetInformationServer(IIS)version5.1
orlater.
ThesolutionsinthisbookwerewrittenusingMicrosoftVisual
Studio2008.MostsolutionswillworkwithVisualStudio2005.
ManyofthesampleswillrunonMicrosoftSQLServer2000.
OthersrequireSQLServer2005andafewrequireSQLServer
2008.Oracle10gisusedtobuildtheOraclesolutions,although
Oracle8iversion3(release8.1.7)orlaterisallyouneed.

P2.4.HowThisBookIsOrganized
Thisbookisorganizedinto12chapters,eachofwhichfocuses
onaparticulartopicincreatingADO.NETsolutions.Eachrecipe

consistsofaspecificproblem,statedasaquestion,followedby
asolutionanddiscussion.Hereisasummaryofeachchapter:
Chapter1,ConnectingtoData
Thesolutionsinthischaptershowhowtoconnecttoa
varietyofdatasourcesfromADO.NET.Connectingtodata
sourcesinvolvesconnectionsstrings,security-relatedissues
includingstoringconnectionstringsandhowtousethem,
thedifferentauthenticationmethodsavailable,andhowto
enabletheusertobuildaconnectionstringatruntime.
Solutionsshowhowtosetup,monitor,andoptimize
connectionpooling,andhowtousetransactionswithpooled
connection.

Chapter2,WorkingwithDisconnectedDataObjects
ADO.NETincludesbothconnectedanddisconnectedclasses.
Thesolutionsinthischapterexplainhowtoworkwiththe
ADO.NETdisconnectedclasses—DataColumn,DataTable,
DataSet,uniqueconstraint,primarykey,foreignkey,and
DataRelation.YouwillalsolearnaboutDataRowarrays,


howtoaccessdatainthem,andhowtoconvertbetweena
DataRowarrayandDataTable.Finally,youwilllearnabout
stronglytypedDataSetobjects,howtocreatethem,and
howtocustomizeaspectsofthem.

Chapter3,QueryingandRetrievingData
Thesolutionsinthischaptershowhowtoretrievedataand
schemasusingSQLstatements,parameterizedSQL
statements,parameterizedstoredprocedures,andbatched

queries,intobothuntypedandstronglytypedDataSet
objects,andDataReaderobjects,andhowtoaccessthe
datainthoseobjects.You'lllearnhowtoworkwith
commandsthatreturnmultipleresultsets.Solutionsshow
howtoretrieveandnavigatehierarchicaldatainboth
untypedandstronglytypedDataSetobjects.You'll
understandhowtoretrievedatausingscalar-valuedand
table-valuedfunctions.Solutionsshowhowtoquerya
DataSetusingLINQandhowtoqueryadatasourceusing
LINQ.Solutionsalsoshowhowtoretrievedatafromatext
fileandfromanExcelworkbook.Finally,youwilllearnhow
toquerydataasynchronouslyusingmessagequeuing.

Chapter4,SearchingandAnalyzingData
Thesolutionsinthischapterfocusonsearchingfor,finding,
andfilteringrecordsinviewsandtables,calculatingvalues
basedonvaluesinthesameorothertables,andnavigating
datarelationsbetweentables.Solutionsshowalternate
techniquestoretrievehierarchicaldata,includingthe
COMPUTEBYandSHAPEclauses.You'lllearnhowtouse
CommonTableExpressions(CTEs)includingrecursive
queries,andhowtoretrieverankedresultsets,random
resultsets,andpivotandunpivottables.Finally,asolution


showshowtoinvokeafunctionforeachrowinaresultset.

Chapter5,AddingandModifyingData
Thischapterfocusesonissuesrelatedtoinsertingand
updatingdata,andusingmessagingtoupdatedata.You'll

learnhowtomanageautoincrementcolumnswithSQL
ServerandsequenceswithOracle.Solutionsshowhowto
addandmodifydatainExcelfilesandtextfiles.You'llsee
howtoretrieveandworkwithDBMSupdateerrors.
Solutionsshowhowtochangeprimarykeysandhowtouse
GUIDprimarykeys,aswellashowtoworkwithmasterdetaildataandhowtoupdateaDataSetwithmanyto
manyrelationships.Asolutionshowshowtoinsertmultiple
rowsusingT-SQLrowconstructorsintroducedinSQL
Server2008.Andyou'llalsolearnhowtocapturechanges
madetodatainaSQLServer2008database.

Chapter6,CopyingandTransferringData
ThischapterfocusesoncopyingdatabetweenADO.NET
disconnectedclasses,convertingbetweenADO.NET
disconnectedclassesandbetweenADOandADO.NET
classes,serializinganddeserializingdata,mergingdata,
encryptingdata,andsecuringlogincredentials.

Chapter7,MaintainingDatabaseIntegrity
Thesolutionsinthischaptershowhowtousemanualand
automatictransactionsandDBMStransactionsfrom
ADO.NET.You'lllearnhowtoidentifyandhandle
concurrencyerrors,setisolationlevels,useSQLServer
pessimisticconcurrencywithlockinghints,updatemasterdetaildatawithoutconcurrencyerrors,andresolvedata


conflicts.

Chapter8,ProgrammaticallyWorkingwithDatain.NET
WindowsandWebFormsUserInterfaces

Thischapterfocusesonprogrammaticallybindingsimple
andcomplexdatatoWebFormsandWindowsForms.You'll
learnhowtomanagemaster-detaildatainWindowsand
WebForms,updatecomplexdata,anddata-bindimages.
You'llunderstandhowtouseglobalizationandlocalization
tocreateapplicationsformultiplecultures.

Chapter9,WorkingwithXMLData
ThesolutionsinthischaptershowhowtouseXMLwith
ADO.NET.You'lllearnhowtoloadschemaanddatafrom
XMLintoaDataSet,andabouttheDiffGramformatand
howtouseittodeterminewhatchangesweremadetoa
DataSet.SolutionsshowhowtoworkwithXMLina
databaseandhowtoworkwithXMLdataandtheSQL
Serverxmldatatype.You'lllearnhowtoreadXMLdata
directlyfromaSQLServerusingFORXML.Solutionsshow
howtouseXPathqueries,controltheformatofXMLoutput,
anduseXMLtemplatequeriestofillaDataSet.Optimizing
updateperformancebybatchingdataupdateswithOpenXML
isalsoillustrated.

Chapter10,Optimizing.NETDataAccess
Thischaptershowshowtoimproveapplicationperformance
andresponsivenesswithasynchronousprocessingaswell
ashowtocancelthoseprocesses,howtocachedatato
improveperformancewhileretrievingdata,andhowtouse
custompagingtoimproveperformanceoverautomatic


paging.SolutionsshowhowtoworkwithBLOBdatainSQL

ServerandOracleandworkwithSQLServeruser-defined
types.You'lllearnhowtooptimizeloadingdataintoaSQL
ServerusingbulkloadingandbatchDataAdapterupdates.
You'llalsolearnhowtoeffectivelydebugSQLServerstored
proceduresusingVisualStudio.Solutionsshowhowto
automaticallyrefreshdatausingpollingandSQLServer
Notifications.Last,you'lllearnhowtowritebothprovideranddatabase-independentADO.NETcode.

Chapter11,EnumeratingandMaintainingDatabaseObjects
Thischaptershowshowtogetschemainformationand
metadatafromdata-bases,managedatabaseobjects,and
enumerateinstalled.NETproviders,OLEDBproviders,and
ODBCdriversusingSQLServerManagementObjects
(SSO),DDL,catalogviews,informationschemaviews,and
systemstoredprocedures.You'lllearnhowtouseADOXto
createaMicrosoftAccessdatabaseandtableswithinthat
database.AsolutionshowshowtogetaSQLServerquery
executionplan.You'llalsolearntoprogrammaticallychange
aSQLServeruserpassword.

Chapter12,SQLServerCLRIntegration
ThischapterprovidesanoverviewofCLRroutinesinSQL
ServerandshowsyouhowtobuildeachtypeofCLR
routine:storedprocedure,scalar-valuedfunction,tablevaluedfunction,aggregatefunction,user-definedtype,DML
trigger,andDDLtrigger.
Finally,AppendixAdiscusseschangesmadetoADO.NETsince
version1.0,coveringbothADO.NET2.0andADO.NET3.5.

P2.5.WhatWasLeftOut



Theprimaryobjectiveofthisbookisnottobeareferenceora
primeraboutADO.NET.Thissecondeditionisexpandedto
includemorerecipesaboutfundamentalADO.NETconceptsand
animprovedarrangementofrecipesthatcanhelpyougetupto
speedquicklyonADO.NET.TheMSDNLibraryisaninvaluable
resource.ItisincludedwithVisualStudioandavailableonline
atSQL
ServerBooksOnline,installedwithMicrosoftSQLServerand
availableinMSDNLibraryOnline,isanexcellentreferenceto
SQLServer.ThisisnotabookabouthowtouseVisualStudioto
build,compile,anddeployapplicationsorhowtouseVisual
StudioIDEfunctionalityrelatedtoADO.NETanddataaccessin
general.

P2.6.ConventionsUsedinThisBook
Thisbookusesthefollowingtypographicconventions:

Italic
UsedforexampleURLs,namesofdirectoriesandfiles,
options,andoccasionallyforemphasis.

Constantwidth
Usedforprogramlistings.Alsousedwithinparagraphsto
refertoprogramelementssuchasnamespaces,classes,
andmethodanddatabasenames.

Constantwidthitalic
Usedfortextthatshouldbereplacedwithuser-supplied
values.



Constantwidthbold
Usedtohighlightportionsofcode.
Thisiconindicatesatip,suggestion,or
generalnote.

Thisiconindicatesawarningorcaution.

P2.7.AbouttheCode
ThisbookcontainsVisualStudioprojectsthatdemonstrate
completesolutionstoproblems.Mostoftheprojectsare
consoleapplicationsusedbecausetheymostsimplyandclearly
demonstratethesolutionwithminimaloverheadandadditional
code.Insomecases,WindowsFormsandWebFormsprojects
areusedtodemonstratesolutionswhereuserinterface
elementsareinvolved.Multiplesolutionstoproblemsare
sometimespresented.Whereappropriate,onealternativewill
berecommended;inothercases,alternativesareequivalent;
makeyourchoicebasedonyourspecificapplication
requirements.
AllofthecodeexamplesinthebookuseC#asaprogramming
language.ListingVisualBasicsolutionswouldhavemadethe
booklessreadable,addedhundredsofpagestoitslength,and
increasedboththecoverpriceandweight.VisualBasiccodefor
allsolutionsinadditiontoC#codeisavailableonthebook's
website, />ThecodeinthebookshowshowtoaccomplishADO.NET
programmingtasksasclearlyandconciselyaspossible.Asa



×