ADO.NET can be used to access a variety ofdata sources including databases such as Microsoft SQL Server,Oracle, and Microsoft Access, as well as XML, OLE DB, and ODBC data sources.. Disc
Trang 1by Bill Hamilton
Publisher: O'Reilly Pub Date: March 15, 2008 Print ISBN-13: 978-0-596-10140-4 Pages: 980
Table of Contents | Index
Overview
This guide is strikingly different from other books on MicrosoftADO.NET Rather than load you down with theory, the new
edition of ADO.NET 3.5 Cookbook gives you more than 200
coding solutions and best practices for real problems you'relikely to face with this technology using Visual Studio 2008 andthe NET 3.5 platform Organized to help you find the topic andspecific recipe you need quickly and easily, this book is morethan just a handy compilation of cut-and-paste C# code
ADO.NET 3.5 Cookbook also offers clear explanations of how
and why each code solution works, and warns you of potentialpitfalls so you can learn to adapt the book's problem-solvingtechniques to different situations This collection of timesavingrecipes covers vital topics including:
Trang 2Ideal for ADO.NET programmers at all levels, from the relativelyinexperienced to the most sophisticated, this new edition coversthe significant 3.5 upgrade, including new programming tools
such as LINQ ADO.NET 3.5 Cookbook offers a painless way for
those of you who prefer to learn by doing when it comes to
expanding your skills and productivity
Trang 3Recipe 1.17 Taking Advantage of Connection Pooling
Trang 4Recipe 2.4 Mapping NET Data Provider Data Types to NETFramework Data Types
Recipe 2.5 Adding a Calculated Column to a DataTable
Recipe 2.6 Creating a Unique Constraint
Recipe 2.7 Creating Single- and Multi-Column Primary KeysRecipe 2.8 Creating an Autoincrementing Primary Key
Recipe 2.18 Replacing Null Values in a Strongly Typed
DataSet
Trang 5Recipe 3.4 Accessing Data Values in a DataReader
Recipe 3.5 Retrieving a Result Set Using a DataTable or aDataSet
Recipe 3.6 Accessing Data Values in a DataTable or DataSetRecipe 3.7 Working with Data in a Strongly Typed DataSetRecipe 3.8 Working with Parent-Child Relations in a
Strongly Typed DataSet
Recipe 3.9 Using a DataView with a Strongly Typed DataSetRecipe 3.10 Testing Whether a Query Returns an EmptyResult Set
Recipe 3.11 Counting Records Meeting Criteria
Recipe 3.12 Determining the Number of Records Returned
in a DataReader
Recipe 3.13 Executing a Query That Returns Multiple ResultSets
Recipe 3.20 Passing a Null Value to a Query Parameter
Trang 6Recipe 3.30 Retrieving Data from a Microsoft Excel
Workbook
Recipe 3.31 Querying Data Asynchronously with MessageQueuing
Chapter 4 Searching and Analyzing Data
Recipe 4.0 Introduction
Recipe 4.1 Determining the Differences in Data BetweenTwo DataSet Objects
Trang 7Recipe 4.15 Retrieving a Pivot and Unpivot Table
Recipe 4.16 Invoking a Function for Each Row in a ResultSet
Recipe 5.4 Getting a Sequence Value from Oracle
Recipe 5.5 Modifying Data in a Microsoft Excel WorkbookRecipe 5.6 Modifying Data in a Text File
Recipe 5.7 Retrieving Update Errors
Recipe 5.8 Adding Parent/Child Rows with AutoincrementingKeys
Recipe 5.9 Adding Records with a GUID Primary Key
Recipe 5.10 Inserting Multiple Rows into a Database TableUsing T-SQL Row Constructors
Recipe 5.16 Controlling Edits, Deletions, or Additions to
Data with a DataView
Recipe 5.17 Overcoming Keyword Conflicts When Using a
Trang 8Recipe 5.18 Capturing Changes to Data in a SQL ServerDatabase
Chapter 6 Copying and Transferring Data
Recipe 6.0 Introduction
Recipe 6.1 Copying Rows from One DataTable to AnotherRecipe 6.2 Copying Tables from One DataSet to AnotherRecipe 6.3 Converting a DataReader to a DataTable
Recipe 7.0 Introduction
Recipe 7.1 Using Distributed Transactions
Recipe 7.2 Using Manual Transactions
Recipe 7.3 Nesting Manual Transactions with the SQLServer NET Data Provider
Recipe 7.4 Using ADO.NET and SQL Server DBMS
Transactions Together
Recipe 7.5 Using a Transaction with a DataAdapter
Recipe 7.6 Avoiding Referential Integrity Problems whenUpdating Data in Related Tables
Trang 9Recipe 8.3 Binding Data to a Web Forms DetailsView
Control
Recipe 8.4 Binding Data to a Web Forms Repeater ControlRecipe 8.5 Binding Data to a Web Forms DataList ControlRecipe 8.6 Binding Data to a Web Forms GridView ControlRecipe 8.7 Modifying and Updating Data in a Web FormsGridView Control
Recipe 8.8 Binding Data to a Web Forms FormView ControlRecipe 8.9 Synchronizing Master-Detail Data in a Web
Forms Application
Recipe 8.10 Displaying an Image from a Database in a WebForms Control
Recipe 8.11 Localizing Client-Side Data in a Web FormsApplication
Recipe 8.12 Loading Data into and Binding a Field to a
Windows Forms Control
Recipe 8.13 Binding Data to a Windows Forms Control
Trang 10Recipe 8.18 Displaying an Image from a Database in a
Windows Forms Control
Recipe 8.19 Binding a Group of Radio Buttons to a WindowsForms Data Field
Recipe 9.4 Creating an XML File That Shows Changes Made
to a DataSet
Recipe 9.5 Synchronizing a DataSet and an XML DocumentRecipe 9.6 Storing and Retrieving XML with a Non-XML DataType Column
Trang 11DataSet
Recipe 10.15 Reading and Writing Large-Value Data withSQL Server
Recipe 10.16 Reading and Writing a SQL Server User-Defined Type (UDT)
Recipe 10.17 Reading and Writing Oracle Large Data
Recipe 10.18 Performing Batch Updates with a DataAdapterRecipe 10.19 Automatically Refreshing a DataTable
Periodically
Recipe 10.20 Automatically Refreshing a DataTable WhenUnderlying Data Changes
Trang 12Chapter 11 Enumerating and Maintaining Database ObjectsRecipe 11.0 Introduction
Recipe 11.1 Enumerating SQL Servers
Recipe 11.2 Retrieving Database Metadata
Recipe 11.3 Retrieving Database Schema Information fromSQL Server
Recipe 11.4 Retrieving Column Default Values from SQLServer
Recipe 11.5 Determining the Length of Columns in a SQLServer Table
Recipe 11.11 Creating DataSet Relationships from SQLServer Relationships
Recipe 11.12 Creating a New Microsoft Access DatabaseRecipe 11.13 Listing Tables in an Access Database
Trang 13Colophon
Index
Trang 14most titles (safari.oreilly.com) For more information, contactour corporate/institutional sales department: (800) 998-9938 orcorporate@oreilly.com
Editor: John Osborn Indexer: Ellen Troutman
Zaig
Production
Editor:
RachelMonaghan
Cover Designer:
KarenMontgomery
Copyeditor: Colleen
Gorman
Interior Designer:
Trang 15trademarks of O'Reilly Media, Inc
Many of the designations used by manufacturers and sellers todistinguish their products are claimed as trademarks Wherethose designations appear in this book, and O'Reilly Media, Inc.was aware of a trademark claim, the designations have beenprinted in caps or initial caps
While every precaution has been taken in the preparation of thisbook, the publisher and author assume no responsibility for
errors or omissions, or for damages resulting from the use ofthe information contained herein
ISBN: 978-0-596-10140-4
[C]
Trang 16Microsoft ADO.NET 3.5 is the latest data access technology fromMicrosoft ADO.NET is a collection of classes that are part of the.NET Framework, and is designed to provide consistent access
to data in loosely coupled n-tier application architectures such
as web services ADO.NET can be used to access a variety ofdata sources including databases such as Microsoft SQL Server,Oracle, and Microsoft Access, as well as XML, OLE DB, and
ODBC data sources
ADO.NET separates data access from manipulation Connectedclasses available in NET data providers connect to a data
source, execute commands, and retrieve results Disconnectedclasses let you access and manipulate data offline and later
synchronize changes with the underlying data source XML
support is tightly integrated with ADO.NET, allowing you to load,access, and manipulate data using XML as well as the
disconnected classes simultaneously
ADO.NET is very different from its predecessor ADO With theincreasing popularity of NET and ADO.NET, there are many
questions from developers about how to solve specific problemsand how to implement solutions most efficiently This book is areference containing solutions and techniques that make usingADO.NET easier and more productive You may have alreadyencountered some of these problems; others you may neversee Some of the solutions are responses to problems that havebeen posted in various discussion groups, while others are realproblems encountered while building applications
This book is organized into chapters, with each chapter
containing solutions (stated as recipes) to a specific problemcategory Each recipe consists of a single question and its
solution followed by a discussion The question-answer formatprovides complete solutions to problems, making it easy to readand use Every recipe contains a complete, documented codesample showing you how to solve the specific problem, as well
Trang 17P2.1 What's New in the Second Edition
A lot has changed since the first edition of this book ADO.NEThas had two significant releases—versions 2.0 and 3.5 SQLServer has also had two major releases with SQL Server 2005and SQL Server 2008 The NET Framework has had three
major releases with versions 2.0, 3.0, and 3.5 And Visual
Studio has had two major releases with Visual Studio 2005 and
2008 This book is updated for the latest version of all of thesetechnologies
This book is a significant revision from the first edition In
addition to the obvious reason for revising this book in order tocover technology changes, I wanted to improve on the first
edition in a number of important ways First, I wanted to makethe book easier to use and more accessible In addition to
updating and adding recipes to cover new or changed
technology and tools, the recipes have been reorganized andnew recipes added to fill in gaps that I and others saw A
number of new recipes in the early chapters address core
concepts in depth The second change that I made was to
rewrite most of the solutions as Windows console applications.While the Windows Forms solutions in the first edition had acertain elegance, I felt that the additional code required and thecomplexity in both building and presenting the solutions
distracted from the core objective of demonstrating solutions toADO.NET problems It also made it difficult to show output fromthe solutions Windows and Web Forms solutions are presented
Trang 18solution And finally, I wanted to make the book more usefuland readable in many small ways—I've clarified and expanded(and in some cases reduced) explanations, increased
consistency in the way solutions are presented, and of coursefixed a few errors along the way
P2.2 Who This Book Is For
You don't have to be an experienced NET developer to use thisbook; it is designed for users of all levels This book providessolutions to problems that developers face every day Reference
or tutorial books can teach general concepts but do not usuallyprovide help solving real-world problems This book teaches byexample, the natural way for most people to learn
Although some of the samples in this book use advanced
techniques, the problems they address are frequently faced bydevelopers with all levels of experience The code samples areall complete, well commented, and thoroughly explained to helpyou apply them and solve your own problems quickly, easily,and efficiently
At the same time, you will understand exactly how and why thesolution works, the requirements, trade-offs, and drawbacks.This book is designed to move you up the learning curve
quickly
This book presents code together with output so that you canuse book without loading the actual code Code generated
automatically by Visual Studio is not shown You don't need toretype the code in this book since it is available in both C# andVisual Basic on the O'Reilly web site
(http://www.oreilly.com/catalog/9780596101404) T-SQL andPL/SQL code is also available for download
P2.3 What You Need to Use This Book
To run the samples in this book, you will need a computer
Trang 19require Microsoft Internet Information Server (IIS) version 5.1
or later
The solutions in this book were written using Microsoft VisualStudio 2008 Most solutions will work with Visual Studio 2005.Many of the samples will run on Microsoft SQL Server 2000.Others require SQL Server 2005 and a few require SQL Server
a solution and discussion Here is a summary of each chapter:Chapter 1, Connecting to Data
The solutions in this chapter show how to connect to a
variety of data sources from ADO.NET Connecting to datasources involves connections strings, security-related issuesincluding storing connection strings and how to use them,the different authentication methods available, and how toenable the user to build a connection string at runtime
Solutions show how to set up, monitor, and optimize
connection pooling, and how to use transactions with pooledconnection
Chapter 2, Working with Disconnected Data Objects
ADO.NET includes both connected and disconnected classes.The solutions in this chapter explain how to work with theADO.NET disconnected classes— DataColumn, DataTable,DataSet, unique constraint, primary key, foreign key, and
DataRelation You will also learn about DataRow arrays,
Trang 20DataRow array and DataTable Finally, you will learn aboutstrongly typed DataSet objects, how to create them, andhow to customize aspects of them
Chapter 3, Querying and Retrieving Data
The solutions in this chapter show how to retrieve data andschemas using SQL statements, parameterized SQL
statements, parameterized stored procedures, and batchedqueries, into both untyped and strongly typed DataSet
objects, and DataReader objects, and how to access thedata in those objects You'll learn how to work with
commands that return multiple result sets Solutions showhow to retrieve and navigate hierarchical data in both
untyped and strongly typed DataSet objects You'll
understand how to retrieve data using scalar-valued andtable-valued functions Solutions show how to query a
DataSet using LINQ and how to query a data source usingLINQ Solutions also show how to retrieve data from a textfile and from an Excel workbook Finally, you will learn how
to query data asynchronously using message queuing
Chapter 4, Searching and Analyzing Data
The solutions in this chapter focus on searching for, finding,and filtering records in views and tables, calculating valuesbased on values in the same or other tables, and navigatingdata relations between tables Solutions show alternatetechniques to retrieve hierarchical data, including the
COMPUTE BY and SHAPE clauses You'll learn how to use
Common Table Expressions (CTEs) including recursive
queries, and how to retrieve ranked result sets, randomresult sets, and pivot and unpivot tables Finally, a solution
Trang 21Chapter 5, Adding and Modifying Data
This chapter focuses on issues related to inserting and
updating data, and using messaging to update data You'lllearn how to manage autoincrement columns with SQL
Server and sequences with Oracle Solutions show how toadd and modify data in Excel files and text files You'll seehow to retrieve and work with DBMS update errors
Solutions show how to change primary keys and how to useGUID primary keys, as well as how to work with master-detail data and how to update a DataSet with many to
many relationships A solution shows how to insert multiplerows using T-SQL row constructors introduced in SQL
Server 2008 And you'll also learn how to capture changesmade to data in a SQL Server 2008 database
Chapter 6, Copying and Transferring Data
This chapter focuses on copying data between ADO.NETdisconnected classes, converting between ADO.NET
disconnected classes and between ADO and ADO.NET
classes, serializing and deserializing data, merging data,encrypting data, and securing login credentials
Chapter 7, Maintaining Database Integrity
The solutions in this chapter show how to use manual andautomatic transactions and DBMS transactions from
ADO.NET You'll learn how to identify and handle
concurrency errors, set isolation levels, use SQL Serverpessimistic concurrency with locking hints, update master-detail data without concurrency errors, and resolve data
Trang 22Chapter 8, Programmatically Working with Data in NET
Windows and Web Forms User Interfaces
This chapter focuses on programmatically binding simpleand complex data to Web Forms and Windows Forms You'lllearn how to manage master-detail data in Windows andWeb Forms, update complex data, and data-bind images.You'll understand how to use globalization and localization
to create applications for multiple cultures
Chapter 9, Working with XML Data
The solutions in this chapter show how to use XML with
ADO.NET You'll learn how to load schema and data fromXML into a DataSet, and about the DiffGram format andhow to use it to determine what changes were made to a
DataSet Solutions show how to work with XML in a
database and how to work with XML data and the SQL
Server xml data type You'll learn how to read XML datadirectly from a SQL Server using FOR XML Solutions showhow to use XPath queries, control the format of XML output,and use XML template queries to fill a DataSet Optimizingupdate performance by batching data updates with OpenXML
is also illustrated
Chapter 10, Optimizing NET Data Access
This chapter shows how to improve application performanceand responsiveness with asynchronous processing as well
as how to cancel those processes, how to cache data to
improve performance while retrieving data, and how to usecustom paging to improve performance over automatic
Trang 23automatically refresh data using polling and SQL ServerNotifications Last, you'll learn how to write both provider-and database-independent ADO.NET code
Chapter 11, Enumerating and Maintaining Database ObjectsThis chapter shows how to get schema information and
metadata from data-bases, manage database objects, andenumerate installed NET providers, OLE DB providers, andODBC drivers using SQL Server Management Objects
(SSO), DDL, catalog views, information schema views, andsystem stored procedures You'll learn how to use ADOX tocreate a Microsoft Access database and tables within thatdatabase A solution shows how to get a SQL Server queryexecution plan You'll also learn to programmatically change
a SQL Server user password
Chapter 12, SQL Server CLR Integration
This chapter provides an overview of CLR routines in SQLServer and shows you how to build each type of CLR
valued function, aggregate function, user-defined type, DMLtrigger, and DDL trigger
routine: stored procedure, scalar-valued function, table-Finally, Appendix A discusses changes made to ADO.NET sinceversion 1.0, covering both ADO.NET 2.0 and ADO.NET 3.5
P2.5 What Was Left Out
Trang 24include more recipes about fundamental ADO.NET concepts and
an improved arrangement of recipes that can help you get up tospeed quickly on ADO.NET The MSDN Library is an invaluableresource It is included with Visual Studio and available online
at http://msdn2.microsoft.com/en-us/library/default.aspx SQLServer Books Online, installed with Microsoft SQL Server andavailable in MSDN Library Online, is an excellent reference toSQL Server This is not a book about how to use Visual Studio tobuild, compile, and deploy applications or how to use Visual
Studio IDE functionality related to ADO.NET and data access ingeneral
Constant width italic
Used for text that should be replaced with user-suppliedvalues
Trang 25Used to highlight portions of code
This icon indicates a tip, suggestion, orgeneral note
elements are involved Multiple solutions to problems are
sometimes presented Where appropriate, one alternative will
be recommended; in other cases, alternatives are equivalent;make your choice based on your specific application
requirements
All of the code examples in the book use C# as a programminglanguage Listing Visual Basic solutions would have made thebook less readable, added hundreds of pages to its length, andincreased both the cover price and weight Visual Basic code forall solutions in addition to C# code is available on the book'sweb site, http://www.oreilly.com/catalog/9780596101404
The code in the book shows how to accomplish ADO.NET
programming tasks as clearly and concisely as possible As a
Trang 261 Exception handling is not included for most solutions.
Omitting exception handling makes solutions easier to
understand by focusing on the key concepts Exception
handling is included and explained thoroughly when it is akey part of the solution Always include good exceptionhandling in your applications— MSDN has excellent
coverage about this topic
2 Inconsistent use of using blocks I've been forced to leave
them out in most cases because they add an extra level ofindent to the code that causes significant formatting
problems because of line shortening I strongly encouragetheir use to guarantee disposition of resources
3 Assigning string literal database connection strings to
variables I do this in nearly every solution and while it
makes the solutions clear, it is terrible practice in real-worldapplications Chapter 1 discusses more suitable approachesfor storing and accessing connection strings
additional Oracle database objects are presented in the
solution
Some solutions require stored procedures Most are written for
Trang 27example SQL Server's T-SQL is somewhat similar to Oracle'sPL/SQL; Oracle users, or users familiar with other proceduralextensions to SQL, should have little difficulty understanding oradapting these stored procedures The disconnected parts ofthe ADO.NET are database-independent and are, for the mostpart, portable with-out modification regardless of the underlyingdata source
P2.8 Using Code Examples
This book is here to help you get your job done In general, youmay use the code in this book in your programs and
documentation You do not need to contact us for permissionunless you're reproducing a significant portion of the code Forexample, writing a program that uses several chunks of codefrom this book does not require permission Selling or
distributing a CD-ROM of examples from O'Reilly books does
require permission Answering a question by citing this bookand quoting example code does not require permission
Incorporating a significant amount of example code from this
book into your product's documentation does require
permission
We appreciate, but do not require, attribution An attributionusually includes the title, author, publisher, and ISBN For
example: "ADO.NET 3.5 Cookbook, Second Edition, by Bill
Hamilton Copyright 2008 O'Reilly Media, Inc., 978-0-596-10140-4."
If you feel your use of code examples falls outside fair use orthe permission given above, feel free to contact us at
permissions@oreilly.com
P2.9 Comments and Questions
We at O'Reilly have tested and verified the information in this
Trang 28bookquestions@oreilly.com
We have a web site for this book where examples, errata, andany plans for future editions are listed You can access this siteat:
online through the O'Reilly Network Safari Bookshelf
Safari offers a solution that's better than e-books It's a virtuallibrary that lets you easily search thousands of top tech books,cut and paste code samples, download chapters, and find quickanswers when you need the most accurate, current information.Try it for free at http://safari.oreilly.com
Trang 29The decision to write the second edition of this book was made
in early 2007 Rather than just adding new recipes to coveradditions and changes since ADO.NET 1.0, I came up with anambitious plan that among other things involved writing newrecipes to fill gaps, making it easier to read and use the bookwithout a computer nearby, reorganizing the book to improvecontinuity, and rewriting all of the code to clarify solutions Theresult is a book that has more than 50 additional recipes and isover 50 percent longer than the original It's been a long effortthat wouldn't have been possible without the efforts and
support of many people
Colleen Gorman edited the second edition of this book, and Ithank her for a careful review and many thoughtful suggestionsand corrections Thanks also to Brian Jepson, who was editorfor the first version of this book—a big job for him because itwas also my first book Brian's encouragement, support, andconstructive criticism helped create a successful book and made
me a better writer in many ways And thanks to Rachel
Monaghan, production editor, and the entire production team atO'Reilly for turning the manuscript into this book
John Osborn, executive editor, conceived the original idea forthe first edition of this book His support throughout that
project contributed to the success of the first edition and madethis sequel possible John is representative of O'Reilly and itsemployees Together, they make the difficult and often tedioustask of writing a book much easier with their support, fairness,directness, professionalism, and honesty I write for O'Reillybecause I believe this publisher is truly dedicated to creating ahigh-quality book that provides great value for the reader A bigplus is that they have a low-bureaucracy environment—
contracts, for example, are short and written in plain English,allowing me to understand them without legal advice
I had the privilege and benefit of working with four outstanding
Trang 30—Lou Franco, Tim Lentine, Zoiner Tejada, and Shawn
Wildermuth I'd like to thank them for reviewing this book socarefully and for providing valuable feedback I've done enoughtechnical reviews to understand and appreciate the effort it
takes to do this well The four of them pointed out where
explanations needed clarification, where more detail was
needed, and also fixed some mistakes I made along the way.This book is better because of their contributions
Thanks to the members of the NET programming communitywho happily and cooperatively share what they know I beganworking with NET in Beta 1 and together with this communitylearned how to be productive with ADO.NET With the help ofthese people, most of whom I don't know and am unlikely tomeet, I was able to understand ADO.NET well enough to writebooks about it I hope this book helps you get through the
challenges that I remember well and admittedly still face fromtime to time
Thanks to my friends and family for their encouragement andsupport They are always there when I need to take my mindoff work—sometimes too often for my own good
And finally, I'd like to thank Nicole She perfectly balances beingboth very supportive and very distracting I think a smart,
funny, and beautiful girl deserves better— I'm glad she doesn'tthink so I love you, doll
Trang 32Recipe 1.0 Introduction
This chapter shows how to connect to a variety of data sourcesfrom ADO.NET; how to handle security-related issues includingstoring connection strings and using different authenticationmethods; and how to set up, monitor, and optimize connectionpooling
1.1.1 ADO.NET Overview
ADO.NET is the part of the NET Framework that connects
applications to data sources and lets you retrieve and updatethe contained data ADO.NET supports a variety of differentdata sources, including relational databases such as MicrosoftSQL Server, Oracle, and Microsoft Access, as well as other datasources such as Microsoft Excel, Outlook, and text files
A NET Framework data provider is used to connect to a datasource, execute commands, and retrieve results The NET
Trang 33to implement a core set of standard interfaces, the capabilitiesand performance of data providers for the same data sourcecan differ significantly
In addition to database-specific providers, the OLE DB NETdata provider allows access to most OLE DB data sources
through OLE DB providers Similarly, the ODBC NET data
provider uses the ODBC drivers to access most ODBC data
sources You can also develop your own data provider to accessproprietary data sources or to meet special requirements
ADO.NET is fundamentally different from ADO despite sharing asimilar name ADO.NET is based on a disconnected architecturewith tight XML integration and is designed specifically to
facilitate development of loosely coupled solutions
ADO.NET code is forward-compatible—ADO.NET code writtenusing NET Framework 1.1 or later will run on later versions ofthe NET Framework
ADO.NET has both connected and disconnected classes Theconnected classes let you retrieve and update data in
underlying data sources The disconnected classes let you
access and manipulate offline the data you retrieved using theconnected classes and later synchronize it with the underlyingdata source using the connected class
Trang 34DataReader
Retrieves a forward-only, read-only data stream from a datasource The DataReader object is specific to the type of
Trang 35SqlDataAdapter object
The disconnected classes are part of the ADO.NET classes in the.NET Framework They provide a consistent programming modelregardless of the data source or data provider The disconnectedclasses include:
DataSet
An in-memory cache of data retrieved from the data source.The DataSet exhibits similar properties to an in-memoryrelational database—for example, data is organized intomultiple tables using DataTable objects, tables can be
related using DataRelation objects, and data integrity can
be enforced using the constraint objects UniqueConstraint
and ForeignKeyConstraint
The DataSet retains no information about the source of thedata used to fill it with data It maintains both current andoriginal versions of data allowing the data source to be
updated with changes at some future time Disconnecteddata classes (DataSet and DataTable) are serializable Thissupports transport-independent marshaling between
application tiers and across a distributed application Youcan also use these classes to persist data independently of
Trang 36classes and XML classes.
Trang 37Connection Pooling
Database connections are a critical and limited resource
Connections must be managed to ensure that an applicationperforms well and is scalable SQL Server and Oracle data
providers provide connection pooling, while the OLE DB andODBC providers use the pooling provided by OLE DB or ODBC,respectively
Connections should be opened as late as possible and closed assoon as possible using the Close()method Alternatively, youcan create the connection in a using block to ensure that thesystem disposes of the connection when the code exits the
block The connection should be used as briefly as possible,meaning that connections should not last longer than a methodcall Connections should not be passed between methods—inaddition to creating performance problems and limiting
scalability, this can lead to security vulnerabilities
Data providers use a connection string containing a collection ofattribute/value pairs to establish the connection with the
Trang 39Recipe 1.0 Introduction
This chapter shows how to connect to a variety of data sourcesfrom ADO.NET; how to handle security-related issues includingstoring connection strings and using different authenticationmethods; and how to set up, monitor, and optimize connectionpooling
1.1.1 ADO.NET Overview
ADO.NET is the part of the NET Framework that connects
applications to data sources and lets you retrieve and updatethe contained data ADO.NET supports a variety of differentdata sources, including relational databases such as MicrosoftSQL Server, Oracle, and Microsoft Access, as well as other datasources such as Microsoft Excel, Outlook, and text files
A NET Framework data provider is used to connect to a datasource, execute commands, and retrieve results The NET
Trang 40to implement a core set of standard interfaces, the capabilitiesand performance of data providers for the same data sourcecan differ significantly
In addition to database-specific providers, the OLE DB NETdata provider allows access to most OLE DB data sources
through OLE DB providers Similarly, the ODBC NET data
provider uses the ODBC drivers to access most ODBC data
sources You can also develop your own data provider to accessproprietary data sources or to meet special requirements
ADO.NET is fundamentally different from ADO despite sharing asimilar name ADO.NET is based on a disconnected architecturewith tight XML integration and is designed specifically to
facilitate development of loosely coupled solutions
ADO.NET code is forward-compatible—ADO.NET code writtenusing NET Framework 1.1 or later will run on later versions ofthe NET Framework
ADO.NET has both connected and disconnected classes Theconnected classes let you retrieve and update data in
underlying data sources The disconnected classes let you
access and manipulate offline the data you retrieved using theconnected classes and later synchronize it with the underlyingdata source using the connected class