Tải bản đầy đủ (.pdf) (611 trang)

ado.net in a nutshell

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 (5.17 MB, 611 trang )

[ Team LiB ]

• Table of C ontents
• Index
• Reviews
• Examples
• Reader Reviews
• Errata
A DO.NET in a Nutshell
By Bill Hamilton, Matthew MacDonald

Publishe r: O 'Re illy
Date
Publishe d
: April 2003
ISBN: 0-596-00361-7
Pa ge s: 620
ADO.NET in a Nutshell is the most complete and c oncise source of ADO .NET information available. Besides being a valuable reference, this book covers a variety of
issues that programmers face when developing web applications or web services that rely on database acc ess. Most examples use Mic rosoft's C# language. T he
book's CD includes an add-in to integrate the reference with Visual Studio .NET help files.
[ Team LiB ]

1 / 611
[ Team LiB ]


• Table of C ontents
• Index
• Reviews
• Examples
• Reader Reviews


• Errata
A DO.NET in a Nutshell
By Bill Hamilton, Matthew MacDonald

Publishe r: O 'Re illy
Date
Publishe d
: April 2003
ISBN: 0-596-00361-7
Pa ge s: 620

Copyright

Prefa ce


Audie nce


Conte nts of T his Bo ok


W ha t's on the C D-R O M


Conve ntio ns U se d in T his Bo o k


Com m e nts a nd Q uestions



Ack no wle dgm ents


Pa rt I: ADO .NET Tutoria l


Chapte r 1. Introd uction


Se ction 1.1. ADO .NET Da ta P rovide rs


Se ction 1.2. C onne cte d and Dis co nnecte d Data



Chapte r 2. .NET Da ta P ro vid e rs


Se ction 2.1. Da ta P rovide rs


Se ction 2.2. Se le cting a Da ta Provider


Se ction 2.3. C rea ting a Custom Da ta Provider




Chapte r 3. Co nnections


Se ction 3.1. C onne ction O bject O vervie w


Se ction 3.2. T he Co nnection String


Se ction 3.3. O pe ning a nd Closing C onne ctions


Se ction 3.4. C onne ction P o o ling



Chapte r 4. Co m m ands


Se ction 4.1. C om ma nd O bject O vervie w


Se ction 4.2. C rea ting a nd Ex e cuting a C o mm and


Se ction 4.3. P aram ete r O bject O ve rvie w


Se ction 4.4. P aram ete rize d C o mm ands



Se ction 4.5. C om ma nds with Sto re d P rocedures


Se ction 4.6. C om ma nds a nd Da ta De finitio n La ng ua g e (DDL)



Chapte r 5. Data Re ade rs


Se ction 5.1. Da taR ea der O bject O verview


Se ction 5.2. P erform ing a Q ue ry with a Data Re ade r


Se ction 5.3. Sto re d Procedure s with the Da taR ea d e r


Se ction 5.4. Da taR ea ders and Sche m a Inform ation



Chapte r 6. Data Sets


Se ction 6.1. C rea ting a n Untype d Da taSet

2 / 611



Se ction 6.2. Work ing with Table s in the Da taSet


Se ction 6.3. Adding a nd R em oving R ela tio ns


Se ction 6.4. Adding C usto m Inform a tion


Se ction 6.5. C loning the Sche ma


Se ction 6.6. C opying the Da taSe t


Se ction 6.7. Me rging Two Da taSe ts


Se ction 6.8. R em oving All Data


Se ction 6.9. R ese tting the Da taSe t


Se ction 6.10. C o mm itting a nd Disca rding C ha ng e s




Chapte r 7. Data Ta ble s


Se ction 7.1. C rea ting a Data Table


Se ction 7.2. Work ing with Colum ns


Se ction 7.3. C onstraints


Se ction 7.4. P rim ary Ke y


Se ction 7.5. R ows


Se ction 7.6. Lo ading Da ta


Se ction 7.7. C om mitting and Disca rd ing Changes


Se ction 7.8. C loning the Sche ma of the Table


Se ction 7.9. C opying the Ta ble



Se ction 7.10. Selecting a Sub se t o f Ro ws


Se ction 7.11. Pe rform ing Aggrega te C a lcula tions


Se ction 7.12. R e moving All Da ta


Se ction 7.13. R e setting the Table


Se ction 7.14. Identifying Errors in the Table


Se ction 7.15. Data Table Eve nts



Chapte r 8. Data Co lum ns


Se ction 8.1. C rea ting Da taC olum ns


Se ction 8.2. C rea ting AutoIncrem ent C olum ns


Se ction 8.3. C rea ting Ex pression Co lum ns



Se ction 8.4. Handling Null Va lues


Se ction 8.5. Mapping .NET Da ta Provider Type s to .NET Fram ework Types



Chapte r 9. Data Ro ws


Se ction 9.1. C rea ting a Data Ro w


Se ction 9.2. Updating R o ws


Se ction 9.3. De leting Rows


Se ction 9.4. Using R ow Sta te Info rm ation


Se ction 9.5. Using R ow Versio n Info rm ation


Se ction 9.6. Accepting or R ejecting Changes to R o ws


Se ction 9.7. Naviga ting P a re nt a nd C hild R o ws



Se ction 9.8. Using R ow Error Inform atio n



Chapte r 10. C onstraints


Se ction 10.1. C o nstra int O bject O vervie w


Se ction 10.2. The Unique C onstraint


Se ction 10.3. The Fore ignKe yC o nstra int



Chapte r 11. Da taR ela tio ns


Se ction 11.1. Data Re lation O bject O vervie w


Se ction 11.2. Navigating Re la tiona l Data



Chapte r 12. Da taViews a nd Da ta Binding



Se ction 12.1. The Da taView a nd Da taViewManage r


Se ction 12.2. Sorting a nd Filtering


Se ction 12.3. Access ing Data Through a Da taView


Se ction 12.4. W indows Da ta Bind ing


Se ction 12.5. ASP.NET Da ta Binding



Chapte r 13. Strongly Type d Data Sets


Se ction 13.1. C re a ting a Strongly Type d Da taSe t


Se ction 13.2. Add ing a R ow


Se ction 13.3. Editing a R ow



Se ction 13.4. Finding a R o w


Se ction 13.5. Null Da ta


Se ction 13.6. Navigating Hierarchical Data


Se ction 13.7. Annota tions



Chapte r 14. Da taAdapte rs


Se ction 14.1. C re a ting Da taAda p ter O b ject

3 / 611


Se ction 14.2. R e trieving Data from the Data Source


Se ction 14.3. R e trieving Sche m a Inform ation from the Da ta Source


Se ction 14.4. Upda ting the Da ta Source



Se ction 14.5. Ma pping Ta ble s a nd C olum ns


Se ction 14.6. AcceptChange sDuringFill


Se ction 14.7. C o ntinueUpdate OnError


Se ction 14.8. Data Ada pte r Eve nts



Chapte r 15. Updating the Da ta So urce


Se ction 15.1. SqlC om ma ndBuilde r C la s s O vervie w


Se ction 15.2. Upda ting a Da ta Source Using C o m m and Build e r


Se ction 15.3. Upda ting a Da ta Source Using C usto m Logic


Se ction 15.4. R e freshing Da ta Afte r Upda ting


Se ction 15.5. R e trieving Up d a ted Values from the Da ta Source



Se ction 15.6. Upda ting Da ta in R elate d Ta ble s


Se ction 15.7. Ha ndling C oncurrency Issue s


Se ction 15.8. O ptim iza tio n



Chapte r 16. Tra nsactions


Se ction 16.1. Ma nua l Tra nsa ctio ns


Se ction 16.2. Isola tion Le ve ls


Se ction 16.3. Save points


Se ction 16.4. Neste d Tra nsactions


Se ction 16.5. Trans a ctions Using a Da taAdapte r


Se ction 16.6. Autom atic Transactions




Chapte r 17. XML and the Da taSe t


Se ction 17.1. Data Set XML Methods


Se ction 17.2. Sha ping DataSe t XML


Se ction 17.3. O ther .NET XML C lasses


Se ction 17.4. Xm lDa taDo cum ent O b ject O verview


Se ction 17.5. Using the Da ta O b jects to Edit XML


Se ction 17.6. SQ L Se rve r 2000 XML



Pa rt II: ADO .NET C o re C lasse s


Chapte r 18. T he Co nnection C la s s



Se ction 18.1. C o mm ents/Trouble sho oting


Se ction 18.2. Prope rtie s R eference


Se ction 18.3. Me thods R efe rence


Se ction 18.4. Eve nts R eference



Chapte r 19. T he Co m m and Class


Se ction 19.1. C o mm ents/Trouble sho oting


Se ction 19.2. Prope rtie s R eference


Se ction 19.3. C o lle ctio ns R e fe rence


Se ction 19.4. Me thods R efe rence




Chapte r 20. T he Pa ra m ete r Class


Se ction 20.1. C o mm ents/Trouble sho oting


Se ction 20.2. Prope rtie s R eference



Chapte r 21. T he Data Re ade r C lass


Se ction 21.1. C o mm ents/Trouble sho oting


Se ction 21.2. Prope rtie s R eference


Se ction 21.3. Me thods R efe rence



Chapte r 22. T he Data Set C lass


Se ction 22.1. C o mm ents/Trouble sho oting


Se ction 22.2. Prope rtie s R eference



Se ction 22.3. C o lle ctio ns R e fe rence


Se ction 22.4. Me thods R efe rence


Se ction 22.5. Eve nts R eference



Chapte r 23. T he Data Table C lass


Se ction 23.1. C o mm ents/Trouble sho oting


Se ction 23.2. Prope rtie s R eference


Se ction 23.3. C o lle ctio ns R e fe rence


Se ction 23.4. Me thods R efe rence


Se ction 23.5. Eve nts R eference



4 / 611


Chapte r 24. T he Data Co lum n Class


Se ction 24.1. C o mm ents/Trouble sho oting


Se ction 24.2. Prope rtie s R eference


Se ction 24.3. C o lle ctio ns R e fe rence



Chapte r 25. T he Data Ro w Class


Se ction 25.1. C o mm ents/Trouble sho oting


Se ction 25.2. Prope rtie s R eference


Se ction 25.3. C o lle ctio ns R e fe rence


Se ction 25.4. Me thods R efe rence




Chapte r 26. T he Co nstraint C la s s


Se ction 26.1. C o mm ents/Trouble sho oting


Se ction 26.2. Prope rtie s R eference


Se ction 26.3. C o lle ctio ns R e fe rence



Chapte r 27. T he Data Re lation Class


Se ction 27.1. C o mm ents/Trouble sho oting


Se ction 27.2. Prope rtie s R eference


Se ction 27.3. C o lle ctio ns R e fe rence



Chapte r 28. T he Data Vie w Class



Se ction 28.1. C o mm ents/Trouble sho oting


Se ction 28.2. Prope rtie s R eference


Se ction 28.3. Me thods R efe rence


Se ction 28.4. Eve nts R eference



Chapte r 29. T he Data Ada pter C la s s


Se ction 29.1. C o mm ents/Trouble sho oting


Se ction 29.2. Prope rtie s R eference


Se ction 29.3. C o lle ctio ns R e fe rence


Se ction 29.4. Me thods R efe rence


Se ction 29.5. Eve nts R eference




Chapte r 30. T he Co m m andBuilde r C lass


Se ction 30.1. C o mm ents/Trouble sho oting


Se ction 30.2. Prope rtie s R eference


Se ction 30.3. Me thods R efe rence



Chapte r 31. T he Transa ction Class


Se ction 31.1. C o mm ents/Trouble sho oting


Se ction 31.2. Prope rtie s R eference


Se ction 31.3. Me thods R efe rence



Pa rt III: AP I Q uick R e fe re nce



Chapte r 32. How to Use This Q uick R efe rence


Se ction 32.1. Finding a Q uick-R eference Entry


Se ction 32.2. R e ading a Q uick-Re ference Entry



Chapte r 33. C onve rting from C # to VB Synta x


Se ction 33.1. Gene ra l C onside ra tio ns


Se ction 33.2. C la sse s


Se ction 33.3. Structures


Se ction 33.4. Interfa ce s


Se ction 33.5. C la ss, Structure , a nd Inte rfa ce Me mbe rs



Se ction 33.6. De le g a tes


Se ction 33.7. Enum era tio ns



Chapte r 34. T he Syste m .Da ta Nam espace


Acce ptR ejectR ule


Com m a ndBe ha vior


Com m a ndType


ConnectionState


Constraint


ConstraintCo llection


ConstraintException



Data Co lum n


Data Co lum nC hangeEve ntArgs


Data Co lum nC hangeEve ntHandle r


Data Co lum nC olle ction

5 / 611


Data Ex ceptio n


Data Re lation


Data Re lationC olle ction


Data Ro w


Data Ro wAction



Data Ro wC hange Eve ntArgs


Data Ro wC hange Eve ntHa ndler


Data Ro wC olle ction


Data Ro wSta te


Data Ro wVersion


Data Ro wView


Data Set


Data SysDe scriptionAttribute


Data Table


Data TableC olle ction



Data Vie w


Data Vie wMa na ge r


Data Vie wR owSta te


Data Vie wSe tting


Data Vie wSe tting C olle ction


DBC oncurrencyException


DbType


Delete dR o wIna ccessible Ex ce ption


Duplica teNam eException


Evalua teEx ception



FillErrorEve ntArgs


FillErrorEve ntHa ndle r


Fo re ignKeyConstraint


IC olum nMa pping


IC olum nMa pping C olle ction


IDa taAda pte r


IDa taP aram ete r


IDa taP aram ete rC olle ction


IDa taR ea der


IDa taR eco rd



IDb C om ma nd


IDb C onne ction


IDb Da taAdapte r


IDb Da taP aram ete r


IDb Transaction


InR owC ha nging Eve ntException


Inte rnalDa taColle ctionBa se


InvalidC onstraintEx ce ption


InvalidEx pressionException


Is o lationLeve l



ITa ble Ma pping


ITa ble Ma ppingCo llection


Ma pp ingType


Me rg e Faile dEve ntArgs


Me rg e Faile dEve ntHandle r


MissingMa ppingActio n


MissingPrim aryKe yExce ption


MissingSche m aActio n


NoNullAllo wedExce p tio n


Pa ram ete rDirection



PropertyAttributes


PropertyC olle ction


Re adO nlyEx ce ption


Ro wNotInTable Ex ce ption


Rule


Schem aType


SqlDbType


State ChangeEve ntArgs


State ChangeEve ntHa ndler


State mentType



StrongTypingEx ception


Syntax ErrorException


Type dDa taSetGe nerato r


Type dDa taSetGe nerato rExce p tio n


Unique Co nstra int

6 / 611


Up da teR owSource


Up da teSta tus


Ve rsio nNotFound Ex ce ptio n


Xm lR e adMode


Xm lW riteMode




Chapte r 35. T he Syste m .Da ta.C om m o n Nam esp a ce


Data Ada p ter


Data Co lum nMa pping


Data Co lum nMa pping C olle ction


Data TableMapping


Data TableMappingC o lle ctio n


DbDa taAda pte r


DBDa taP e rm issio n


DBDa taP e rm issio nAttrib ute



DbDa taR eco rd


DbEnum erato r


Ro wUpdate dEve ntArgs


Ro wUpdatingEventArgs



Chapte r 36. T he Syste m .Da ta.SqlClie nt Nam espa ce


SqlClientP e rm iss ion


SqlClientP e rm iss ionAttribute


SqlCo m m and


SqlCo m m andBuilde r


SqlCo nne ction



SqlData Ada pte r


SqlData Re ade r


SqlError


SqlErrorCo llection


SqlException


SqlInfo Me ssage Eve ntArgs


SqlInfo Me ssage Eve ntHa ndler


SqlPa ra m ete r


SqlPa ra m ete rCo llection


SqlR o wUpda tedEve ntArgs



SqlR o wUpda tedEve ntHa ndle r


SqlR o wUpda tingEve ntArgs


SqlR o wUpda tingEve ntHandle r


SqlTrans a ction



Chapte r 37. T he Syste m .Da ta.O leDb Nam esp a ce


O le Db C om ma nd


O le Db C om ma ndBuilder


O le Db C onne ction


O le Db Da taAdapte r


O le Db Da taR ea der



O le Db Error


O le Db ErrorC o lle ctio n


O le Db Ex ce ptio n


O le Db InfoMessa ge Eve ntArgs


O le Db InfoMessa ge Eve ntHandle r


O le Db P aram ete r


O le Db P aram ete rC o lle ctio n


O le Db P erm iss ion


O le Db P erm iss ionAttribute


O le Db R owUpdate dEventArgs



O le Db R owUpdate dEventHa nd le r


O le Db R owUpdatingEve ntArgs


O le Db R owUpdatingEve ntHa nd le r


O le Db Sche ma Guid


O le Db Transaction


O le Db Type



Chapte r 38. T he Syste m .Da ta.SqlTypes Nam esp a ce


INullable


SqlBinary



SqlBo ole an


SqlByte


SqlCo m pa reO ptions


SqlDateTim e

7 / 611



SqlDecim al


SqlDouble


SqlGuid


SqlInt16


SqlInt32



SqlInt64


SqlMo ne y


SqlNullVa lueExce p tio n


SqlSingle


SqlString


SqlTruncate Ex ceptio n


SqlType Ex ception



Pa rt IV: Appendix es


Appe ndix A. ADO .NET P rovide rs


Se ction A.1. T he SQ L Se rve r P rovide r



Se ction A.2. T he O LE DB P rovide r


Se ction A.3. T he O DBC .NET Provider


Se ction A.4. T he O ra cle .NET P rovide r


Se ction A.5. T he O DP.NET P rovide r



Appe ndix B. ADO .NET XML Ex tensions


Se ction B.1. co de ge n Nam espa ce


Se ction B.2. m sda ta Nam espa ce


Se ction B.3. diffgr Nam espace



Appe ndix C . Microsoft Data Engine (MSDE)



Se ction C .1. Installing MSDE


Se ction C .2. MSDE Ess e ntials


Se ction C .3. Adding the Northwind Da ta


Se ction C .4. Migrating MSDE to SQ L Se rve r



Type , Me tho d, Property, and Fie ld Index


A-L


M-Z



Colophon

Inde x
[ Team LiB ]


8 / 611

[ Team LiB ]

Copyright
Copyright © 2003 O'Reilly & A s sociates, Inc.
Printed in the United States of America.
Published by O 'Reilly & As sociates, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472.
O 'Reilly & A ssociates books may be purchased for educational, business, or sales promotional use. O nline editions are also available for most titles
(). For more information, contact our corporate/institutional sales department: (800) 998-9938 or
Nutshell Handbook, the Nutshell Handbook logo, and the O'Reilly logo are registered trademarks of O'Reilly & Associates, Inc. Many of the des ignations used by
manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and O'Reilly & A ssociates, Inc.
was aware of a trademark claim, the des ignations have been printed in caps or initial caps. Microsoft, the .NET logo, Visual Basic .NET, V isual Studio .NET,
A DO .NET, Windows, and Windows 2000 are regis tered trademarks of Microsoft C orporation. The association between the image of an Afric an s poonbill and the topic
of A DO .NET is a trademark of O'Reilly & Ass oc iates, Inc.
While every precaution has been taken in the preparation of this book, the publis her and authors assume no responsibility for errors or omissions, or for damages
resulting from the use of the information contained herein.
[ Team LiB ]


9 / 611
[ Team LiB ]

Preface
A lmost every software application is driven by data. Usually, this data is centralized in a relational databas e system such as SQ L Server, O racle, or DB2. In the
.NET world, you access this information using Microsoft's lates t data access technology: A DO .NET.
Like many other .NET technologies, A DO .NET bears some superficial similarities to its predecessor (in this cas e, ADO ). However, ADO .NET als o includes some
dramatic changes and a few surpris ing innovations. It has a disconnected programming model tailored for distributed applications and the Web, built-in support for
XML serialization, practical data binding, and an extensible set of interfaces that let you c reate custom data providers.
Learning to use ADO .NET takes a little work, but the rewards are well worth it. With the help of this reference, you'll be up and running before you know it.
[ Team LiB ]



10 / 611
[ Team LiB ]

Audience
This book is intended primarily as a reference and learning tool for experienced developers who need to master A DO .NET. You don't need experience with A DO , but
you should be familiar with .NET basics such as ass emblies, events, metadata, and the Common Language Runtime. If you are new to .NET, you'll be well served by
starting with an introductory work such as .NET Framework Essentials by Thuan L.Thai and Hoang Lam (O'Reilly and A ssociates, Inc.).
This book als o assumes you know the basic s of developing databas e applications. The examples in this book use the Northwind sample database, whic h is
automatically installed with SQL Server and available with the freely installable, scaled-down version, Microsoft Data Engine (MSDE). If you use a different database
product, you won't be able to run all the examples as written, although all the c oncepts will still apply.
Finally, to get the most out of this book, it's strongly recommended that you know the SQL language. If you're new to SQL, you should supplement this book with
such books as SQL in a Nutshell by Kevin Kline and Daniel Kline (O 'Reilly). You may also want to read books that target the specific SQ L extensions used by your
database product, such as Oracle PL/SQL Programming by Steven Feuerstein and Bill Pribyl and Transact-SQL Programming by Kevin Kline, Lee Gould, and A ndrew
Zanevsky (both O 'Reilly books ).
[ Team LiB ]


11 / 611
[ Team LiB ]

Contents of This Book
This book consists of a tutorial section that explains A DO .NET concepts , a class library references that describes every ADO .NET type, and several appendixes
with s upplementary information.
The best place to begin your exploration of A DO .NET is with the foundation chapters in P art I. Here's a brief des cription of those chapters:
Chapter 1
Introduces the basic ADO .NET objects and their roles.
Chapter 2
Describes the clas ses that make up an A DO .NET data provider and the providers available with the .NET framework.
Chapter 3

Describes how to create a connection to a data source using ADO .NET and handle connection pooling.
Chapter 4
Describes the first level of ADO .NET: connection-based programming to perform live record updates, inserts, and deletions. A lso shows how to interact with
stored procedures and create parameterized commands.
Chapter 5
Explains how to retrieve the results of a query from a data source using a read-only, forward-only cursor. Also briefly demonstrates how you can write
provider-agnostic A DO .NET code
Chapter 6
Introduces the heart of A DO .NET's disconnected data features: the DataSet.
Chapter 7
Introduces the DataTable objec t that stores one or more rowsets in a DataSet.
Chapter 8
Explains the DataColumn object, which together with Constraint objects defines the schema for a DataTable.
Chapter 9
Explains the DataRow object, which contains an individual row of data in a DataTable.
Chapter 10
Describes Constraint objects, which enforce unique and foreign key constraints of data.
Chapter 11
Describes the DataRelation, which helps you navigate parent-child relationships and maintain referential integrity within the DataSet.
Chapter 12
Describes the DataView object, which represents a custom view of the data within a DataTable. The chapter discusses using the DataView to s ort, filter, and edit
data and to perform data binding in both Web and Windows Forms .
Chapter 13
Describes strongly typed DataSet classes, how to generate and use them, and considerations about their use.
Chapter 14
Describes how the DataAdapter c lass bridges the disconnected classes in A DO .NET with the underlying data source. The chapter explains how to retrieve
data from the data source, place that data into a DataSet, and subsequently update modifications to the DataSet back to the underlying data source.
Chapter 15
Describes how to commit updates made in a DataSet to the original data source.
Chapter 16

Describes how to start and manage client-initiated transactions, and compares them with stored procedure transactions and distributed CO M+
transactions.
Chapter 17
Explains how ADO .NET works with XML. You'll learn what you can and can't control with ADO .NET 's XML serialization, how DiffGrams store versioning
information, and how web s ervic es encode the DataSet for transmission. Also introduces the XML features built into SQ L Server 2000.
Part II, documents the core ADO .NET classes. A separate chapter is provided for each c lass, with an essential description of its properties, methods, and events.
Part III, provides a high-level reference of the ADO .NET namespaces. When you design or code an application, you'll often find it useful to refer to this condensed
clas s information.
Namespac es described in the reference include:
System.Data
System.Data.Common
System.Data.OleDb
System.Data.SqlClient
System.Data.SqlTypes
Part IV , encompasses the following:
A ppendix A
Includes provider tables that show the key types for each provider, the data type mappings, and other miscellaneous details. A lso describes some providers
that aren't included with .NET.
A ppendix B
Explains the custom XML namespaces used when serializing a DataSet with versioning information or creating a typed DataSet schema.

12 / 611
A ppendix C
Briefly describes MSDE, the freely dis tributable scaled-down version of SQ L Server that can be used for desktop applications.
Glossary
Contains an alphabetic listing of the types and members found in Part III . You can use it to determine the namespace to which a particular type or member
belongs.
[ Team LiB ]



13 / 611
[ Team LiB ]

What's on the CD-ROM
The C D-RO M that accompanies the print version of this book contains a c opy of ADO.NET in a Nutshell for Microsoft Visual Studio .NET. This software plugs direc tly
into Microsoft V isual Studio .NET and makes the c ontents of Part III of this book, API Quick Reference, available to you as a fully integrated member of Visual Studio
.NET Dynamic Help.
By making ADO.NET in a Nutshell a part of your Vis ual Studio .NET development environment, you gain the following benefits:
Constantly updated Dynamic Help links to relevant Quick Reference entries as you write C# code (these links appear in a separate Dynamic Help window link
group named O 'Reilly Help )
Links to both Quick Reference topics and Microsoft documentation topics when you use either the Help Search facility or interactive Index
A cces s to the O'Reilly web site, , for additional books and articles on Visual Basic .NET, C #, and the .NET Framework
Cross links from Q uick Reference topics to related topics in MSDN documentation.
For more information on ADO.NET in a Nutshell for Microsoft Visual Studio .NET, please read the release notes on the CD-RO M.
To us e ADO.NET in a Nutshell for Microsoft Vis ual Studio .NET, you must be running a version of Vis ual Basic .NET or V isual Studio .NET on your computer or laptop.
To install ADO.NET in a Nutshell for Microsoft V isual Studio .NET:
1. Place the CD-RO M in the CD-RO M player.
2. If you are running V isual Studio .NET 2003, double-click on the file named ADONETinaNutshell2003.msi. If you are still running V isual Studio .NET 2002,
double-click on the file named ADONETinaNutshell2002.msi.
3. Follow the instructions contained in the install program windows. Be sure to read and accept the terms of the software license before proceeding.
To uninstall ADO.NET in a Nutshell for Microsoft Vis ual Studio .NET, repeat the previous procedure, but c lick on the Remove button when the program prompts you to
select an install option.
Making the ADO.NET in a Nutshell Q uick Reference section available as a V isual Studio .NET plug-in is a new venture for O 'Reilly & A ssociates and Microsoft. We
want very much to hear your comments and ideas. P lease send any comments to:

If you disc over errors in content or encounter any problems in using this product, please report them to:

[ Team LiB ]



14 / 611
[ Team LiB ]

Conventions Used in This Book
The following typographic conventions are used in this book:
Italic is used for:
Pathnames, filenames, program names, and utilities
Internet addresses, such as domain names and URLs
New terms where they are defined
Constant width is used for:
Command lines and options that should be typed verbatim
Names and keywords in C# programs, including method, variable, and class names
Events, event handlers, objects, properties, class es, methods, controls, values, operators, and namespaces
Code samples
XML element tags
This icon designates a note, whic h is an important aside to the nearby text.
This icon designates a warning relating to the nearby text.
[ Team LiB ]


15 / 611
[ Team LiB ]

Comments and Questions
Please address comments and questions concerning this book to the publis her:
O 'Reilly & A ssociates , I nc.
1005 Gravenstein Highway North
Sebastopol, C A 95472
(800) 998-9938 (in the United States or C anada)
(707) 829-0515 (international/local)

(707) 829-0104 (fax)
There is a web page for this book that lists errata, examples, or any additional information. You can access this page at:
/>To comment or ask technical questions about this book, send email to:

For more information about books, conferences, Resource Centers, and the O 'Reilly Network, s ee the O 'Reilly web site at:

[ Team LiB ]


16 / 611
[ Team LiB ]

Acknowledgments
This book couldn't have been written without the help of many individuals at O 'Reilly, including Robert Denn, Nancy Kotary, John O sborn, and Brian Jepson, who kept
the book on track through its revision process. We also owe heartfelt thanks to the technical reviewers, including Shawn Wildermuth, who offered valuable comments
throughout.
Without the s upport of these people and many more at O 'Reilly, the book would never have been written.
Bill
I would like to thank Molly for her encouragement and support. I love you Molly—you're the best! I would also like to thank my friends and family who not only put up
with me, but cheer me on.
Matthew
I'd like to thank my parents (all four of them) and my endlessly supportive wife Faria, whom I love dearly. Without them all, this book would never have been written!
CD-ROM Acknowledgments
ADO.NET in a Nutshell for Visual Studio .NET is the work of many individuals. Mike Sierra of O 'Reilly converted the ADO .NET namespace API references to Microsoft
Help 2.0 format and added the XML tags needed to integrate their content with the V isual Studio .NET Dynamic Help sys tem. He was assisted by Lenny Muellner
and Erik Ray. Greg Dic kerson and the O'Reilly Tech Support group tested each prerelease build of the software. Kipper York and Shane McRoberts of the Microsoft
Help team provided invaluable technical ass istance at critical moments, and Erik P romislow of Active State built the install package that makes our Help files an
integral part of the Visual Studio .NET developer environment. John O sborn managed the development and releas e of the product. Frank Gocinski of the Visual
Studio .NET third-party integration program was instrumental in making us full VSIP partners. A spec ial tip of the hat as well to Rob Howard who understood our
original vision and helped us make the right connections to get this project off the ground

[ Team LiB ]


17 / 611
[ Team LiB ]

Part I: ADO.NET Tutorial
[ Team LiB ]


18 / 611
[ Team LiB ]

Chapter 1. Introduction
A DO .NET is a new programming model built upon the .NET Framework, sharing a common type system, design patterns and naming c onventions. The stated goals
of A DO .NET are to:
Provide a disconnected (offline) data architecture in addition to supporting c onnected operation
Integrate tightly with XML
Interact with a variety of data sources through a common data representation
O ptimize data source access
A DO .NET is designed to provide consis tent access to data sources. This is accomplished through A DO .NET data providers that provide methods for connecting to
data sources as well as retrieving, manipulating, and updating data in both c onnected and disconnected environments.
[ Team LiB ]


19 / 611
[ Team LiB ]

1.1 ADO.NET Data Providers
A n ADO .NET data provider connects to a data source such as SQ L Server, Oracle, or an O LE DB data source, and provides a way to execute commands against

that data source in a consistent manner that is independent of the data source and data source-specific functionality. However, aside from a core set of similar
capabilities, there is no guarantee that identical functionality will be available in each data provider. This is due to differences between data sources (for example,
SQ L Server provides many more capabilities than A ccess) and provider implementations (for example, both Microsoft and O racle offer A DO .NET providers for
O racle's data server with slight implementation differences).
A complete .NET data provider includes the following clas s es:
Connection
Connects to the data source.
Command
Executes commands against the data source.
DataReader
A forward-only, read-only connected result set.
ParameterCollection
Stores all parameters related to a Command and the mappings of both table and column names to the DataSet c olumns.
Parameter
Defines parameters for parameterized SQ L statements and stored procedures.
Transaction
Groups statements modifying data into work units that are either committed in their entirety or c ancelled.
DataAdapter
Bridges the connected components to the dis connected components, allowing a DataSet and DataTable to be filled from the data source and later reconciled
with the data source.
The classes for the different providers inherit from a common set of classes and implement a common set of interfaces to provide consistent functionality regardles s
of the provider. Each data provider uses a unique namespace to logic ally name and group the classes in the data provider and prevent collisions in the assemblies.
The .NET Framework Version 1.0 ships with SQ L Server and O LE DB data providers. T he .NET Framework Version 1.1 als o ships with both O DBC and Oracle data
providers; thes e providers must be downloaded and installed separately with .NET Framework Version 1.0. O ther .NET data providers can be downloaded and
installed separately with either version of the .NET Framework. Specific data providers are discussed in more detail in Chapter 2.
Because all .NET data providers present a consistent interface, porting an A DO .NET applic ation from one provider to another is a straightforward task. The
examples in this book use the .NET SQ L Server data provider except when dis cussing O LE DB specific functionality (e.g., s c hema views). Any significant
differences between the SQ L Server and O LE DB data providers are also discussed throughout the book.
[ Team LiB ]



20 / 611
[ Team LiB ]

1.2 Connected and Disconnected Data
A s mentioned earlier, ADO .NET supports two different programming environments: connected and dis c onnected.
The connected environment provides forward-only, read-only acc ess to data in the data source and the ability to execute commands against the data source. The
connected classes provide a common way to work with connected data regardles s of the underlying data source. T hey include Connection, Command, DataReader,
Transaction, ParameterCollection, and Parameter clas s es.
The disconnected environment allows data retrieved from the data source to be manipulated and later reconciled with the data source. The dis c onnected classes
provide a common way to work with disconnected data regardles s of the underlying data source. T hey include the DataSet, DataTable, DataColumn, DataRow, Constraint,
DataRelationship, and DataView classes.
Finally, ADO .NET introduces the connected DataAdapter class to bridge the data source and disc onnected clas ses by way of the connected classes. The DataAdapter
is an abstraction of the connected class es that simplifies filling the disconnected DataSet or DataTable clas ses with data from the data source and updating the data
source to reflect any changes made to the dis connected data. Figure 1-1 shows the relationship between the connected and disc onnected clas s es in ADO .NET.
Figure 1-1. The conne cted and disconnected ADO.NET classes
1.2.1 Connected Classes
The following class es are used by A DO .NET to communicate directly with the data source:
Connection
Maintains information required to connect to the data source through a c onnection string. The connection string contains information such as the name of
the data source and its location, and authorization credentials and settings. The Connection class has methods to open and clos e the connection, for
transactions to be initiated on the connection, as well as control other properties of the connection.
Command
Executes SQ L statements or stored procedures against the data source. The command class has a ParameterCollection object containing Parameter objects
that allow parameterized SQ L statements and stored procedures to be used against the data source.
DataReader
Provides connected forward-only, read-only access to the data source. I t is optimized for speed. The DataReader is instantiated through a Command object.
Parameter
A llows parameters for both parameterized queries and stored procedures to be defined and set to appropriate values. T he Parameter class is access ed
through the ParametersCollection object within a Command object. It supports input and output parameters as well as return values from stored procedures.

Transaction
A llows transactions to be created on a c onnection so that multiple changes to data in a data source are treated as a single unit of work and either all
committed or cancelled.
DataAdapter
Bridges the data source and the disconnected DataSet or DataTable clas s es. The DataAdapter wraps the connected classes to provide this functionality. It
provides a method to retrieve data into a disconnected object and a method to reconcile modified data in the disconnected object with the data source. T he
CommandBuilder c lass can generate the logic to reconcile changes in s imple situations; custom logic can be supplied to deal with complex situations and
optimize performance.
1.2.2 Disconnected Classes
The following ADO .NET classes allow data to be retrieved from the data set, examined and modified offline, and rec onciled with the data source through the
DataAdapter:
DataSet
Provides a consis tent way to deal with disconnected data completely independently of the data source. T he DataSet is ess entially an in-memory relational
database, s erving as a container for the DataTable, DataColumn, DataRow, Constraint, and DataRelation objects .
The XML format serializes and transports a DataSet. A DataSet can be acces sed and manipulated either as XML or through the methods and properties of the
DataSet interchangeably; the XmlDataDocument class represents and synchronizes the relational data within a DataSet object with the XML Document O bject
Model (DO M).
DataTable
A llows dis c onnected data to be examined and modified through a c ollection of DataColumn and DataRow classes. The DataTable allows constraints such as
foreign keys and unique constraints to be defined using the Constraint class.

21 / 611
DataColumn
Corresponds to a column in a table. The DataColumn c lass stores metadata about the structure of the column that, together with constraints, defines the
sc hema of the table. T he DataColumn can also create expression c olumns based on other columns in the table.
DataRow
Corresponds to a row in a table and can examine and update data in the DataTable. T he DataTable expos es DataRow objects through the DataRowCollection
object it contains. The DataRow caches changes made to data contained in its columns, storing both original and current values. This allows changes to be
cancelled or to be later reconciled with the data source.
Constraint

A llows constraints to be placed on data stored within a DataTable. Unique and foreign key constraints can be c reated to maintain data integrity.
DataRelation
Provides a way to indicate a relationship between different DataTable objects within a DataSet. T he DataRelation relates columns in the parent and child tables
allowing navigation between the parent and child tables and referential integrity to be enforced through cascading updates and deletes.
DataView
A llows data, once retrieved into a DataSet or DataTable, to be viewed in different ways. It allows data to be s orted based on column values and for a subset of
the data to be filtered so that only rows matching specified criteria are displayed.
Chapter 2 examines .NET data providers in more detail and describes the way in which they provide connected functionality and serve as a bridge to disconnected
functionality.
[ Team LiB ]


22 / 611
[ Team LiB ]

Chapter 2. .NET Data Providers
The .NET Framework 1.0 ships with the Microsoft SQ L Server .NET data provider and O LE DB .NET data provider. The .NET Framework 1.1 als o includes both the
O racle and O DBC .NET data providers. A .NET data provider connects to the data source and executes commands, either to retrieve results or to modify the data in
the data source. I t is possible to create a .NET data provider for practically any data source: Exchange servers, XML documents, and SQL databases other than
those .NET supports out of the box. Figure 2-1 shows the relationship between the A DO .NET data providers that ship with .NET, the data sources that they access,
and the dis c onnected ADO .NET classes.
Figure 2-1. ADO.NET data providers
[ Team LiB ]


23 / 611
[ Team LiB ]

2.1 Data Providers
The most commonly used .NET data providers are described in the following sec tions.

2.1.1 Microsoft SQL Server
The SQ L Server .NET data provider s hips with the .NET Framework. I t uses the Tabular Data Stream (TDS) protocol to s end requests to and receive responses from
the SQ L Server. This provider delivers very high performance because TDS is a fast protocol that can access Microsoft SQ L Server directly without an OLE DB or
O DBC layer and without CO M interop. The SQ L Server .NET data provider can be used with Microsoft SQ L Server 7.0 or later. To acces s earlier versions of
Microsoft SQL Server, the OLE DB .NET data provider with the SQ L Server OLE DB provider (SQ LO LEDB) should be used. The SQ L Server .NET data provider
clas ses are located in the System.Data.SqlClient namespace.
2.1.2 OLE DB
The O LE DB .NET data provider ships with the .NET Framework. It communicates with a data source using a data source-specific OLE DB provider through CO M
interop. The OLE DB provider, in turn, communicates directly with the data source using native OLE DB calls.
The O LE DB .NET data provider supports OLE DB interfaces later than Version 2.5. A s a result, s ome O LE DB providers, including those for Microsoft Exc hange
Server and Internet Publishing, aren't supported. Also, the O LE DB .NET data provider can't be used with the OLE DB provider for ODBC (MSDA SQ L). To acces s
O DBC data, use the O DBC .NET data provider disc ussed later in this chapter.
The O LE DB.NET data provider classes are located in the System.Data.OleDb namespace.
2.1.3 ODBC
The O DBC .NET data provider is installed as an add-in component to the .NET Framework Version 1.0 and ships with the .NET Framework Version 1.1. The provider
communicates with the data source using native ODBC drivers through CO M interop.
The following ODBC drivers are guaranteed compatible with the ODBC .NET data provider:
Microsoft SQL Server O DBC Driver
Microsoft ODBC Driver for O racle
Microsoft Acc ess (Jet) O DBC Driver
The O DBC .NET data provider clas ses are located in the Microsoft.Data.Odbc namespace in Version 1.0 of the .NET Framework. In Version 1.1, the namespac e
changes to System.Data.Odbc.
The Microsoft O DBC .NET data provider can be downloaded from the .NET Framework section of />2.1.4 Oracle
The O racle .NET data provider is installed as an add-in component to the .NET Framework Version 1.0 and ships with the .NET Framework Version 1.1. This
provider acces ses an O racle database using the Oracle Call Interface (O C I). The Oracle .NET data provider can be used with O racle 8i Release 3 (8.1.7) or later.
Us e the OLE DB .NET data provider with the Oracle O LE DB provider (MSDA ORA ) for earlier versions of Orac le. O racle 9i is required to access UTF16 databases
because UTF16 is a new feature in O racle 9i.
The Microsoft O racle .NET data provider classes are located in the System.Data.OracleClient namespace in both Versions 1.0 and 1.1 of the .NET Framework.
The Microsoft O racle .NET data provider can be downloaded from the .NET Framework section of rosoft.c om/downloads.
A dditionally, O racle has a .NET data provider available at />2.1.5 SQLXML Managed Classes

The SQ LXML Managed Classes can acces s the functionality of SQLXML 3.0 from within .NET applications. Using SQLXML Managed Classes, XML data can be
retrieved from a SQ L Server, processed, and sent back to the SQ L Server to apply updates. The SQ LXML Managed Classes can't be considered a full .NET data
provider because only partial implementations of the Command, Parameter, and DataAdapter classes are included.
The SQ LXML Managed Classes are located in the Microsoft.Data.SqlXml namespace.
The SQ LXML Managed Classes can be downloaded from the SQ L Server Development sec tion of />2.1.6 Other Providers
In addition to the data providers mentioned earlier, there are many other native managed providers available or under development. Table 2-1 lists sources for more
information about other native .NET data providers.
Table 2-1. Other nativ e .NET data prov iders
Organization Data source URL
Core Lab O racle, MySQ L http://crlab.c om
DataDirect Technologies O racle and Sybase
dataWeb TurboDB bodb.c om
Enterprise Information Designs MySQ L
MySQ L MySQ L
PostgreSQ L PostgreSQ L
SourceForge MySQ L, Firebird
A s mentioned, many databases and data sources that currently don't have native managed providers, including DB2, I nformix, and Interbase, can be access ed
using the .NET OLE DB data provider and an OLE DB provider.

24 / 611
[ Team LiB ]


25 / 611

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

Tải bản đầy đủ ngay
×