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

ado.net cookbook

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 (2.53 MB, 442 trang )

[ Team LiB ]

• Table of C ontents
• Index
• Reviews
• Examples
• Reader Reviews
• Errata
A DO.NET Cookbook
By Bill Hamilton

Publishe r: O 'Re illy
Pub Date : Septe mber 2003
ISBN: 0-596-00439-7
Pa ge s: 624
ADO.NET Cookbook is a comprehensive collection of over 150 solutions and best practices for everyday dilemmas. For each problem addressed in the book, there's a
solution a short, focused piece of code that programmers can insert directly into their applications The diverse solutions presented here will prove invaluable over
and over again, for ADO .NET programmers at all levels, from the relatively inexperienced to the most sophisticated.
[ Team LiB ]

1 / 442
[ Team LiB ]


• Table of C ontents
• Index
• Reviews
• Examples
• Reader Reviews
• Errata
A DO.NET Cookbook


By Bill Hamilton

Publishe r: O 'Re illy
Pub Date : Septe mber 2003
ISBN: 0-596-00439-7
Pa ge s: 624

Copyright

Prefa ce


W ho T his Bo ok Is Fo r


W ha t You Need to Use This Bo o k


How T his Bo ok Is O rganize d


W ha t Was Le ft O ut


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


Abo ut the C ode



Configura tio n File s


Platfo rm Notes


Com m e nts a nd Q uestions


Ack no wle dgm ents

Chapte r 1. Co nnecting to Da ta


Intro duction


Re cipe 1.1. C onne cting to a n O DBC Da ta So urce


Re cipe 1.2. C onne cting to a Microsoft Ex cel Workboo k


Re cipe 1.3. C onne cting to a Pa ss wo rd -Prote cte d Access Data base


Re cipe 1.4. C onne cting to a Secure d Acce ss Da taba s e


Re cipe 1.5. C onne cting to a n Acce ss Da taba s e from ASP.NET



Re cipe 1.6. Using a n IP Addre s s to C onne ct to SQ L Se rve r


Re cipe 1.7. C onne cting to a Nam ed Insta nce o f SQ L Se rve r or Microso ft Da ta Engine (MSDE)


Re cipe 1.8. C onne cting to SQ L Serve r Using Integrate d Se curity from ASP.NET


Re cipe 1.9. C onne cting to a n O ra cle Da taba se


Re cipe 1.10. C o nne cting to Excha nge or O utlo o k


Re cipe 1.11. W riting Da tabase -Inde p e nde nt C ode


Re cipe 1.12. Storing C o nne ction Strings


Re cipe 1.13. Using the Da ta Link P rope rtie s Dia lo g Box


Re cipe 1.14. Mo nito ring C o nne ctio ns


Re cipe 1.15. Tak ing Adva nta ge o f C o nne ctio n P ooling



Re cipe 1.16. Setting C o nne ctio n P ooling O ptions


Re cipe 1.17. Using Transa ctions with Poo le d Connections


Re cipe 1.18. C ha nging the Da tabase for a n O pe n C onne ction


Re cipe 1.19. C o nne cting to a Te x t File

Chapte r 2. Re trieving and Ma naging Da ta


Intro duction


Re cipe 2.1. R etrie ving Hie ra rchical Da ta into a Data Set


Re cipe 2.2. Building a Data Set P ro gram matica lly


Re cipe 2.3. C rea ting a Strongly Typed Da taSet


Re cipe 2.4. P ro ce ssing a Batch SQ L State ment



Re cipe 2.5. Using a Web Service a s a Da ta So urce


Re cipe 2.6. Accessing De lete d R ows in a Da taTa ble

2 / 442


Re cipe 2.7. C ounting R ecords in a Data Re ade r


Re cipe 2.8. Mapping .NET Da ta Provider Da ta Typ e s to .NET Fra m ework Da ta Type s


Re cipe 2.9. R eturning a n O utput P a ram ete r Using a Data Re ade r


Re cipe 2.10. R a ising and Ha ndling Sto re d P rocedure Errors


Re cipe 2.11. Te sting fo r No Re cords


Re cipe 2.12. R e trieving Stored P roce d ure R eturn Va lue s Using a Da taR ea der


Re cipe 2.13. Exe cuting SQ L Se rver Use r-De fine d Sca la r Functions



Re cipe 2.14. Pa ss ing Null Values to Pa ra m ete rs


Re cipe 2.15. R e trieving Upd a te Errors


Re cipe 2.16. Ma pping Ta ble a nd Co lum n Nam es Betwe en the Data Source and Data Set


Re cipe 2.17. Disp la ying C olum ns from a R e late d Data Table


Re cipe 2.18. C o ntrolling the Nam es Use d in a Strongly Type d Data Set


Re cipe 2.19. R e pla cing Null Value s in a Strong ly Type d Da taSe t


Re cipe 2.20. R e trieving Data from a n O racle P ack a ge


Re cipe 2.21. Using P a ra me teriz e d SQ L Sta tem ents


Re cipe 2.22. Q ue rying Data As ynchrono us ly with Me s s a ge Q ueuing

Chapte r 3. Se arching and Ana lyzing Data


Intro duction



Re cipe 3.1. Filtering a nd Sorting Da ta


Re cipe 3.2. Using Ex p re s sion C o lum ns to Display Ca lcula ted Values


Re cipe 3.3. De term ining the Differences in Data Be tween Two Da taSe t O bjects


Re cipe 3.4. Naviga ting Betwe en P arent a nd C hild R e cords Us ing a Da taR ela tio n


Re cipe 3.5. Lo caliz ing Clie nt-Side Data in a Web Fo rm s Application


Re cipe 3.6. C om bining Data in Ta ble s from Hete roge ne o us Da ta So urces


Re cipe 3.7. Using Ex p re s sion C o lum ns to Display Aggregate Va lues


Re cipe 3.8. Find ing Ro ws in a Data Ta ble


Re cipe 3.9. Find ing Ro ws in a Data Vie w


Re cipe 3.10. Selecting the To p n R ows in a Da taTa b le



Re cipe 3.11. Getting Type d Da taR o ws from Da taVie ws


Re cipe 3.12. Filte ring fo r Null Value s


Re cipe 3.13. Exe cuting Q ue rie s Tha t Use C OMP UT E BY


Re cipe 3.14. Using the Shape La nguage to R etrieve Hie ra rchical Da ta

Chapte r 4. Adding a nd Mo d ifying Da ta


Intro duction


Re cipe 4.1. Using Auto-Increm enting Co lum ns W itho ut C ausing C onflicts


Re cipe 4.2. Ge tting an Identity Colum n Va lue from SQ L Se rve r


Re cipe 4.3. Ge tting an Auto Num be r Value from Microso ft Access


Re cipe 4.4. Ge tting a Se que nce Value fro m O ra cle



Re cipe 4.5. Adding P a rent/C hild R o ws with Auto -Increm enting Ke ys


Re cipe 4.6. Adding R ecords with a GUID Prim ary Ke y


Re cipe 4.7. Updating a Da ta So urce with Da ta from a Diffe re nt Data So urce


Re cipe 4.8. Updating a P rim ary Ke y Va lue


Re cipe 4.9. Ge tting Stored Proce dure P a ram ete r Inform atio n a t R untim e


Re cipe 4.10. Upda ting a Da taSet with a Many-to -Ma ny R elatio nship


Re cipe 4.11. Upda ting Se rve r Da ta Using a Web Service


Re cipe 4.12. Upda ting Se rve r Da ta Using .NET R em oting


Re cipe 4.13. Upda ting Da ta Asynchrono usly Using Me ss a ge Q ueuing


Re cipe 4.14. O vercom ing Ke yword C o nflicts W hen Using C o mm andBuild e rs


Chapte r 5. Co pying a nd Transfe rring Data


Intro duction


Re cipe 5.1. C opying Ro ws from O ne Da taTable to Ano ther


Re cipe 5.2. C opying Table s from O ne Da taSe t to Ano the r


Re cipe 5.3. C onve rting a Data Re ade r to a Da taSe t


Re cipe 5.4. Se rializing Da ta


Re cipe 5.5. De seria lizing Da ta


Re cipe 5.6. Me rging Da ta


Re cipe 5.7. Transm itting a Da taSet Se cure ly


Re cipe 5.8. Transfe rring Lo g in C re de ntia ls Se cure ly



Re cipe 5.9. Lo ading a n ADO R ecordset into a Da taSet


Re cipe 5.10. C o nverting a Da taSet to a n ADO R e cords e t


Re cipe 5.11. Exporting the R esults of a Q ue ry a s a String


Re cipe 5.12. Exporting the R esults of a Q ue ry to a n Array

Chapte r 6. Ma inta ining Da taba se Inte grity


Intro duction


Re cipe 6.1. C rea ting a Class That Pa rticipa tes in a n Autom atic Tra nsa ction


Re cipe 6.2. Using Ma nual Trans a ctions


Re cipe 6.3. Nesting Ma nua l Transactions with the SQ L Serve r .NET Da ta P rovide r


Re cipe 6.4. Using ADO .NET a nd SQ L Se rve r DBMS Trans a ctions Togethe r


Re cipe 6.5. Using a Transa ction with a Da taAdapte r



Re cipe 6.6. Avo iding Re ferential Inte grity P roble ms W he n Upda ting the Da ta Source

3 / 442


Re cipe 6.7. Enforcing Busine ss R ules with C o lum n Ex pressions


Re cipe 6.8. C rea ting C onstraints , P rim aryKe ys, R elatio nships Base d on Multiple Co lum ns


Re cipe 6.9. R etrie ving C onstraints from a SQ L Serve r Data base


Re cipe 6.10. C he ck ing fo r Co ncurrency Violations


Re cipe 6.11. R e solving Da ta Co nflicts


Re cipe 6.12. Using Transa ction Isolation Le vels to Prote ct Da ta


Re cipe 6.13. Im ple me nting Pe ssim istic Co ncurrency W ithout Using Da taba s e Lo ck s


Re cipe 6.14. Spe cifying Locking Hints in a SQ L Se rve r Da tabase


Chapte r 7. Binding Da ta to .NET User Inte rfa ce s


Intro duction


Re cipe 7.1. Binding Sim ple Da ta to Web Form s C o ntrols


Re cipe 7.2. Binding Com ple x Da ta to Web Form s C o ntrols


Re cipe 7.3. Binding Da ta to a Web Form s Da taList


Re cipe 7.4. Binding Da ta to a Web Form s Da taGrid


Re cipe 7.5. Editing a nd Updating Data in a Web Form s Da taGrid


Re cipe 7.6. Synchronizing Ma ste r-Deta il We b Fo rm s Da taGrids


Re cipe 7.7. Displa ying an Im age from a Da tab a se in a We b Fo rm s C ontrol


Re cipe 7.8. Displa ying an Im age from a Da tab a se in a W ind o ws Form s Control



Re cipe 7.9. Binding a Group of R adio Buttons in a W indows Form


Re cipe 7.10. C re a ting Custom C olum ns in a W indo ws Form s Da taGrid


Re cipe 7.11. Po p ulating a W ind o ws Fo rm s Co m bo Bo x


Re cipe 7.12. Binding a W indows Da taGrid to Ma ste r-De tail Data


Re cipe 7.13. Lo a ding a W indows PictureBo x with Im ag e s Stored by Acce ss a s O LE O bjects


Re cipe 7.14. Using a Da taVie w to C ontrol Edits, De le tio ns, o r Additio ns in W indows Form s


Re cipe 7.15. Add ing Se arch Ca pa b ilitie s to W indows Form s


Re cipe 7.16. Dyna m ica lly C rea ting C rysta l R epo rts


Re cipe 7.17. Using ADO .NET De sign-Tim e Fe atures in Classe s W ithout a GUI

Chapte r 8. Wo rk ing with XML


Intro duction



Re cipe 8.1. Using XSD Sche m a File s to Lo ad a nd Save a Data Set Structure


Re cipe 8.2. Sa ving a nd Lo ading a Data Set from XML


Re cipe 8.3. Synchronizing a Da taSe t with a n XML Docum ent


Re cipe 8 Storing XML to a Da taba se Field


Re cipe 8.5. R ea ding XML Da ta Dire ctly from SQ L Se rve r


Re cipe 8.6. Using XP a th to Q ue ry Data in a Data Set


Re cipe 8.7. Transform ing a Data Set Using XSLT


Re cipe 8.8. C rea ting a n XML File Tha t Shows C ha nge s Ma d e to a Da taSet


Re cipe 8.9. Fo rm atting C olum n Values W he n O utputting Da ta as XML


Re cipe 8.10. Filling a Data Set Using a n XML Te m pla te Q uery



Re cipe 8.11. Using a Sing le Stored Proce dure to Upd a te Multip le Changes to a SQ L Se rve r
Data ba se

Chapte r 9. O p tim izing .NET Da ta Access


Intro duction


Re cipe 9.1. Filling a Da taSet Asynchrono usly


Re cipe 9.2. C anceling a n Asynchro nous Q ue ry


Re cipe 9.3. C aching Da ta


Re cipe 9.4. Im proving Pa g ing Pe rfo rm ance


Re cipe 9.5. P erform ing a Bulk Inse rt with SQ L Se rve r


Re cipe 9.6. Im proving Data Re ade r P erform ance with Type d Accessors


Re cipe 9.7. Im proving Data Re ade r P erform ance with C olum n O rdina ls



Re cipe 9.8. De bugging a SQ L Se rve r Stored P roce d ure


Re cipe 9.9. Im proving Pe rform ance W hile Filling a Da taSe t


Re cipe 9.10. R e trieving a Single Value from a Q uery


Re cipe 9.11. R e ading and W riting Bina ry Da ta with SQ L Se rve r


Re cipe 9.12. R e ading and W riting Bina ry Da ta with O racle


Re cipe 9.13. Pe rform ing Batch Update s with a Da taAdapte r


Re cipe 9.14. R e freshing a Data Set Autom atica lly Using Exte nde d Properties

Chapte r 10. Enum erating and Ma inta ining Da tab a se O bjects


Intro duction


Re cipe 10.1. Listing SQ L Serve rs



Re cipe 10.2. R e trieving Data base Schem a Info rm atio n from SQ L Se rve r


Re cipe 10.3. R e trieving Co lum n Defa ult Va lue s from SQ L Se rve r


Re cipe 10.4. De term ining the Le ngth of C olum ns in a SQ L Serve r Table


Re cipe 10.5. C o unting Re cords


Re cipe 10.6. C re a ting a New Access Data base


Re cipe 10.7. C re a ting a New SQ L Se rve r Data base


Re cipe 10.8. Add ing Tables to a Da taba s e


Re cipe 10.9. Getting a SQ L Se rve r Q uery P lan


Re cipe 10.10. Com pa cting a n Acce ss Da taba s e


Re cipe 10.11. Crea ting Da taSet Re la tions hips from SQ L Se rve r Re lations hips


4 / 442


Re cipe 10.12. Ge tting SQ L Se rve r C olum n Me tada ta W ithout R e turning Data


Re cipe 10.13. Lis ting Ins talle d O LE DB P roviders


Re cipe 10.14. Lis ting Tables in an Access Data ba se


Re cipe 10.15. Crea ting a Table in the Da taba s e from a Data Table Sche ma


Re cipe 10.16. Lis ting Ins talle d O DBC Drivers

Appe ndix A. C onve rting from C # to VB Synta x


Se ction A.1. Ge ne ral C o nsideratio ns


Se ction A.2. C lasses


Se ction A.3. Structure s


Se ction A.4. Inte rfaces



Se ction A.5. C lass, Structure, and Inte rfa ce Me mbe rs


Se ction A.6. De legate s


Se ction A.7. Enum erations

Colophon

Inde x
[ Team LiB ]


5 / 442
[ 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. The association between the image of a white spoonbill and the topic of
A DO .NET is a trademark of O'Reilly & A s sociates, Inc. A ctiveX, FrontPage, I ntelliSense, JScript, MSDN, V isual Basic, Visual C++, V isual Studio, Windows, and
Windows NT are registered trademarks, and Visual C# and V isual J# are trademarks of Microsoft C orporation.

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 ]


6 / 442
[ Team LiB ]

Preface
Microsoft ADO .NET is the latest data access technology from Microsoft. ADO .NET is a collection of classes that are part of the .NET Framework, and is designed to
provide consistent acces s to data in loosely coupled n-tier application architectures such as web services. A DO .NET can be used to access a variety of data
sources including databases such as Microsoft SQ L Server, O racle, and Microsoft A ccess, as well as XML, OLE DB, and ODBC data sources.
A DO .NET separates data access from manipulation. Connected classes available in .NET data providers connect to a data source, execute commands, and retrieve
results. Disconnected clas s es let you access and manipulate data offline and later synchronize changes with the underlying data source. XML support is tightly
integrated with A DO .NET, allowing you to load, ac c ess, and manipulate data us ing XML as well as the dis connected classes simultaneously.
A DO .NET is very different from its predec essor A DO . With the increas ing popularity of .NET and A DO .NET, there are many questions from developers about how to
solve specific problems and how to implement solutions mos t efficiently. T his book is a reference containing solutions and techniques that make using ADO .NET
easier and more productive. You may have already encountered some of these problems; others you may never see. Some of the solutions are responses to
problems that have been posted in various disc ussion groups, while others are real problems encountered while building applications.
This book is organized into chapters, with eac h chapter containing solutions (stated as recipes) to a specific problem category. Each recipe consists of a single
question and its solution followed by a dis cussion. The question-answer format provides complete solutions to problems, making it easy to read and use. Nearly
every recipe contains a complete, doc umented c ode sample showing you how to solve the specific problem, as well as a discussion of how the underlying technology
works and a discussion of alternatives, limitations, and other considerations when appropriate. All of the code—both C# and V B.NET—is available from the web site
( />[ Team LiB ]


7 / 442
[ Team LiB ]

Who This Book Is For

You don't have to be an experienced .NET developer to use this book; it is designed for users of all levels. This book provides solutions to problems that developers
face every day. Reference or tutorial books can teach general concepts but do not usually provide help solving real-world problems. This book teaches by example;
the natural way for most people to learn.
While some of the samples in this book use advanced techniques, these problems are frequently fac ed by developers with all levels of experience. T he code samples
are all complete, well commented, and thoroughly explained to help you apply them and solve your own problems quickly, easily, and efficiently. A t the same time,
you will understand exactly how and why the solution works, the requirements, trade-offs, and drawbacks. This book is designed to move you up the learning curve
quickly. T he solutions show good programming discipline and techniques to further help less experienced developers.
You don't need to retype the c ode in this book since it is available on the O'Reilly web site ( Only code important to the
solution is listed in this book. Enough c ode is presented so that the book can be used without loading the actual code. The book does not list user interface code, its
background code, or code generated automatically by V isual Studio .NET.
[ Team LiB ]


8 / 442
[ Team LiB ]

What You Need to Use This Book
To run the samples in this book, you will need a computer running Windows 2000 or later. The Web Forms solutions require Microsoft I nternet Information Server
(IIS) Version 5 or later.
To open and compile the samples in this book, you will need V isual Studio .NET 2003. Most of the samples require Microsoft SQ L Server 2000. O racle solutions
require O racle 8i Version 3 (release 8.1.7) or later.
Some of the solutions require classes that are not installed with either Visual Studio .NET or SQ L Server. These classes are mentioned in the solutions and in the
installation notes bundled with the example code.
[ Team LiB ]


9 / 442
[ Team LiB ]

How This Book Is Organized

This book is organized into 10 chapters, each of whic h focus on a particular topic in creating ADO .NET solutions. Each recipe consists of a specific problem, stated
as a question, followed by a solution and disc ussion. To give you an overview of this book's contents, the following paragraphs summarize each chapter:
Chapter 1
The solutions in this chapter show how to c onnect to a variety of data sources from A DO .NET. C onnec ting to data sources involves connections strings,
security-related iss ues including storing connection strings and how to use them, and the different authentication methods available. Solutions show how to
set up, monitor, and optimize connection pooling.
Chapter 2
The DataSet is a data source-independent, dis c onnected, in-memory relational database that provides sophistic ated navigational capabilities. The solutions
in this chapter s how how to retrieve data using SQ L statements, parameterized SQ L statements, stored procedures, and batched queries, into both untyped
and s trongly typed DataSet objects. Solutions show how to understand the data that is returned. You'll learn how to use messaging and web services to
retrieve data.
Chapter 3
The solutions in this chapter focus on s earching for rec ords in views and tables, calculating values based on values in the same or other tables , and
navigating data relations between tables. You'll understand how to use globalization and localization to create applic ations for multiple cultures. Solutions
show alternate techniques to retrieve hierarchical data, including the COMPUTE BY and SHAPE clauses.
Chapter 4
This chapter focuses on iss ues related to inserting and updating data, and using web services , remoting, and messaging to update data. You'll learn how to
manage auto-increment columns with SQ L Server and sequences with O racle. Solutions show how to change primary keys and how to use GUI D primary
keys, as well as how to work with master-detail data.
Chapter 5
This chapter focuses on copying data between ADO .NET classes and between ADO and A DO .NET classes, serializing and deserializing data, merging data,
encrypting data, and securing login credentials.
Chapter 6
The solutions in this chapter show how to use manual and automatic transactions and DBMS transac tions from A DO .NET. You'll learn how to identify and
handle concurrency errors, how to set isolation levels , how to simulate pessimistic concurrency, how to use SQL Server pessimistic concurrency with
loc king hints, and how to update master-detail data without concurrency errors.
Chapter 7
This chapter focuses on binding simple and complex data to Web Forms and Windows Forms . You'll learn how to manage mas ter-detail data in Web Forms,
how to update complex data, how to data-bind images, and how to use C rys tal Reports dynamically at runtime. Solutions show how to control us er editing of
data with data views. For applications without a user interface, you'll learn how to use design-time features in classes without a user interface.

Chapter 8
The solutions in this chapter show how to use XML with A DO .NET. You'll learn how to load schema and data from XML into a DataSet, about the DiffGram
format and how to use it to determine what changes were made to a DataSet. You'll als o learn how to read XML data directly from a SQ L Server using FOR XML.
Solutions show how to use XPath queries , how to control the format of XML output, and how to use XML template queries to fill a DataSet. Optimizing update
performance by batching data updates with OpenXML is shown.
Chapter 9
This chapter shows how to improve applic ation performance and 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 use custom paging to improve performance over automatic paging. Solutions
show how to work with BLO B data in SQ L Server and O racle. You'll learn how to optimize loading data into a SQ L Server using bulk loading with SQ L XML and
how to optimize updating data with batch updates by handling DataAdapter events. You'll als o learn how to effectively debug s tored procedures using Visual
Studio .NET.
Chapter 10
This chapter shows how to get schema information and metadata from databases, manage database objects , and enumerate installed OLE DB providers and
O DBC drivers using DDL, SQ L-DMO , information schema views , and s ystem s tored procedures. You'll learn how to use JRO to manage a Mic rosoft A c c ess
database. A solution shows how to get a query exec ution plan using the SQ L Server SET statement.
In some cases, recipes are related. Where appropriate, recipes reference other solutions.
The A ppendix A contains a brief tutorial, Converting from C# to VB Syntax.
[ Team LiB ]


10 / 442
[ Team LiB ]

What Was Left Out
This book is not a reference or a primer about ADO .NET. A good primer and reference to ADO .NET is ADO.NET in a Nutshell by Bill Hamilton and Matthew MacDonald
(O 'Reilly). The MSDN Library is also invaluable. It is included with V isual Studio .NET and available online at rosoft.c om/library/default.asp. SQ L
Server Books Online, installed with Microsoft SQ L Server and available in MSDN Library O nline, is an excellent reference to SQL Server.
This is not a book about how to use V isual Studio .NET to build, compile, and deploy applic ations. See Mastering Visual Studio .NET by Ian Griffiths, Jon Flanders, and
Chris Sells (O 'Reilly) for excellent coverage of these topics.
[ Team LiB ]



11 / 442
[ Team LiB ]

Conventions Used in This Book
This book uses the following typographic conventions:
Constant width
Us ed for program listings. A lso used within paragraphs to refer to program elements such as namespaces, classes, and method names.
Bold constant width
Us ed in program listings, to highlight an important part of the code.
//
Ellipses in C # code indicate text that has been omitted for clarity.
<! >
Ellipses in XML schemas and documents indicate text that has been omitted for clarity.
Italic
Us ed for example URLs, names of direc tories and files, options, and oc c as ionally for emphasis .
This icon indicates a tip, suggestion, or general note.
This icon indicates a warning or caution.
[ Team LiB ]


12 / 442
[ Team LiB ]

About the Code
Nearly every recipe in this book contains a code sample. The sample is not just a fragment, but rather a complete solution that takes the form of either a Windows
Forms or a Web Forms application.
In many cases, the solution code contains additional code that lets you explore alternatives, test performance, and see information that will help you understand
key concepts. Multiple solutions are sometimes presented. Where appropriate, one alternative will be rec ommended; in other c ases, alternatives are equivalent and

selection should be based on your specific application requirements.
Complete error handling is not included for each solution. O mitting error handling makes the solution easier to understand by foc using on the key concepts. Error
handling that is a key part of the solution is included and explained thoroughly. These principles can als o be applied to other solutions in this book.
A ll of the code examples in the book use C# as a programming language. Listing V B.NET solutions would have made the book less readable, added hundreds of
pages to its length, and increased both cover price and weight. VB.NET code for all solutions in addition to C# code is available on the book's web site,
There are also releas e notes explaining installation and configuration.
.NET introduced the C # programming language as well as V B.NET. Both languages compile to the same intermediate language (IL) used by .NET and are more
similar than different; differences are mainly syntac tic. T hey can also be mixed within the s ame solution. Most VB.NET programmers have little trouble converting
C# samples. The book C# and VB.NET Conversion Pocket Reference by Jose Mojica (O 'Reilly) provides a concise (139-page) reference with all the details about
converting between C# and V B.NET. The Appendix A covers this as well.
The solutions using SQ L Server use the Northwind sample database. Some solutions require additional tables and stored procedures; these can be installed using
the installation script from the example code from the web site. T he Oracle solutions use either the SC OT T sample databas e installed with Oracle, or, in some cas es
where SCO TT is inadequate, a version of Northwind that has been ported to Oracle. Instructions for creating this database are also available in the example code.
Some solutions require stored procedures. Most are written for Mic rosoft SQ L Server; however, in some cases Oracle is used because the recipe solves a problem
specific to O racle—identity columns in SQ L Server versus sequences in O racle, for example. SQ L Server's T-SQ L is somewhat similar to O rac le's PL/SQ L; O racle
users, or users familiar with other procedural extensions to SQ L, should have little difficulty understanding or adapting these stored procedures. The disconnected
parts of the A DO .NET are databas e independent and are, for the most part, portable without modification regardless of the underlying data source.
[ Team LiB ]


13 / 442
[ Team LiB ]

Configuration Files
Configuration files are XML-based files that can be used to store application settings so that they can be c hanged as needed without recompiling the application.
The Windows Forms and Web Forms solutions each use a configuration file to store all configuration settings.
The configuration file for all Web Forms solutions contains the following elements.
Web.config
<appSettings>
<add key="DataConnectString"

value="Data Source=(local);user id=sa;password=;Initial Catalog=Northwind;" />
</appSettings>
The configuration file for all Windows Forms solutions follows.
App.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="Project_Directory" value="c:\\AdoDotNetCookbook\\CS\\" />
<add key="Temp_Directory" value="c:\\temp\\" />

<add key="Sql_ConnectString" value=
"Data Source=(local);user id=sa;password=;Initial Catalog=Northwind;" />
<add key="Sql_SqlAuth_ConnectString" value=
"Data Source=(local);Initial Catalog=Northwind;User ID=sa;password=;" />
<add key="Sql_Master_ConnectString" value=
"Data Source=(local);Integrated security=SSPI;Initial Catalog=master;" />
<add key="Sql_Msde_ConnectString" value="Data Source=(local)\vsdotnet;
Integrated security=SSPI;Initial Catalog=Northwind;" />
<add key="OleDb_ConnectString" value="Provider=SQLOLEDB;
Data Source=(local);Integrated Security=SSPI;Initial Catalog=Northwind;" />
<add key="OleDb_SqlAuth_ConnectString" value="Provider=SQLOLEDB;
Data Source=(local);Initial Catalog=Northwind;User ID=sa;password=;" />
<add key="OleDb_Oracle_ConnectString" value=
"Provider=MSDAORA;Data Source=ORCL;User Id=scott;Password=tiger;" />
<add key="OleDb_Shape_ConnectString" value="Provider=MSDataShape;
Data Provider=SQLOLEDB;Data Source=(local);
Initial Catalog=Northwind;Integrated Security=SSPI;" />
<add key="OleDb_Msde_ConnectString" value="Provider=SQLOLEDB;
Data Source=(local)\vsdotnet;Integrated security=SSPI;
Initial Catalog=Northwind;" />


<add key="Oracle_ConnectString" value=
"Data Source=ORCL;User Id=ADODOTNETCOOKBOOK;Password=password;" />
<add key="Oracle_Scott_ConnectString" value=
"Data Source=ORCL;User Id=scott;Password=tiger;" />

<add key="Odbc_ConnectString" value=
"DRIVER={SQL Server};SERVER=(local);UID=sa;PWD=;DATABASE=Northwind;" />

<add key="MsAccess_ConnectString" value="Provider=Microsoft.Jet.OLEDB.4.0;
Data Source=c:\\AdoDotNetCookbook\\DB\\MsAccess\\Northwind.mdb;" />
<add key="MsAccess_Secure_ConnectString"
value="Provider=Microsoft.Jet.OLEDB.4.0;
Data Source=c:\\AdoDotNetCookbook\\DB\\MsAccess\\NorthwindPassword.mdb;" />
<add key="MsAccess_Database_Filename"
value="c:\\AdoDotNetCookbook\\DB\\MsAccess\\Northwind.mdb" />
<add key="MsAccess_SecureMdw_Filename"
value="c:\\AdoDotNetCookbook\\DB\\MsAccess\\Northwind.mdw" />

<add key="Excel_0115_ConnectString" value='Provider=Microsoft.Jet.OLEDB.4.0;
Data Source=c:\AdoDotNetCookbook\CS\Chapter01\Categories.xls;
Extended Properties="Excel 8.0;HDR=YES";' />

<add key="TextFile_0119_ConnectString"
value='Provider=Microsoft.Jet.OLEDB.4.0;
Data Source=c:\AdoDotNetCookbook\CS\Chapter 01\;
Extended Properties="text;HDR=yes;FMT=Delimited";' />
</appSettings>
</configuration>
[ Team LiB ]



14 / 442
[ Team LiB ]

Platform Notes
The solutions in this book were developed using V isual Studio .NET version 1.1. The differences between Version 1.1 and Version 1.0 of the .NET Framework are
significant overall, but do not affect A DO .NET much. A complete list of differences between Version 1.1 and Version 1.0 of the .NET Framework can be found at
hanges.aspx.
[ Team LiB ]


15 / 442
[ Team LiB ]

Comments and Questions
We at O 'Reilly have tested and verified the information in this book to the best of our ability, but mistakes and oversights do occur. Pleas e let us know about errors
you may find, as well as your s uggestions for future editions, by writing to:
O 'Reilly & A ssociates
1005 Gravenstein Highway North
Sebastopol, C A 95472
(800) 998-9938 (in the U.S. or Canada)
(707) 829-0515 (international or local)
(707) 829-0104 (fax)
To ask technical questions or comment on the book, send email to:

We have a web site for this book where examples, errata, and any plans for future editions are listed. You c an access this site at:
/>For more information about this book and others, see the O 'Reilly web site:

[ Team LiB ]



16 / 442
[ Team LiB ]

Acknowledgments
This book was originally conceived in March 2002. I t's been a long effort that wouldn't have been possible without the help and support of many people.
Brian Jepson, editor, provided valuable advice about content, structure, and writing. His suggestions about grammar, voice, and s tyle made this book better in ways
that nobody will ever know about. Brian also pus hed me to get this book done by s etting aggress ive timelines that kept me up nights—for this I'm also grateful. I've
truly enjoyed working with him on this project.
John O sborn, executive editor, conceived the original idea for this book and believed in and supported this project. John is representative of O 'Reilly and its
employees. Together they make the diffic ult, often (very) tedious, task of writing a book much eas ier with their fairness, directness, professionalism, and honesty. I
write for O 'Reilly because I believe this publisher is truly dedicated to creating a high-quality book that provides great value for the reader. A big plus is that they
have a low-bureaucracy environment—contracts, for example, are s hort and written in plain Englis h, allowing me to understand them without legal advice.
Technical reviewer Shawn Wildermuth provided valuable feedback about the technical content. He pointed out where my explanations needed clarification and where
they needed more detail. Shawn also suggested some great, new recipe ideas that I have included in this book.
The A DO .NET programming community gladly shared what they know. I began working with .NET in Beta 1 and, together with this community, learned how to be
productive with ADO .NET. With the help of these people, most of whom I don't know and am unlikely to meet, I was able understand A DO .NET well enough to write
this book. I hope that this book makes it easier for you to get through the tough times that I remember well.
Thanks als o to my friends and family for their encouragement and support. T hey are always there when I need to take my mind off work.
Finally, thanks to Molly for her support, understanding, patience, and encouragement. I know that in my time off I don't want to think about technology. Molly is an
artis t and I can't imagine or understand how she put up with me talking about this book when I was struggling with a topic or with motivation. And she did this
without c omplaining or yawning. I love you Molly—you make me laugh and smile.
[ Team LiB ]


17 / 442
[ Team LiB ]

Chapter 1. Connecting to Data

Introduction
Recipe 1.1. C onnecting to an O DBC Data Source
Recipe 1.2. C onnecting to a Microsoft Excel Workbook
Recipe 1.3. C onnecting to a P assword-Protected A ccess Databas e
Recipe 1.4. C onnecting to a Sec ured Acc ess Database
Recipe 1.5. C onnecting to an A ccess Databasefrom A SP.NET
Recipe 1.6. Using an IP Address to C onnect to SQL Server
Recipe 1.7. C onnecting to a Named I nstance of SQL Server or Microsoft Data Engine (MSDE)
Recipe 1.8. C onnecting to SQ L Server Using Integrated Security from ASP.NET
Recipe 1.9. C onnecting to an O racle Database
Recipe 1.10. Connecting to Exc hange or O utlook
Recipe 1.11. Writing Database-Independent Code
Recipe 1.12. Storing C onnection Strings
Recipe 1.13. Using the Data Link Properties Dialog Box
Recipe 1.14. Monitoring C onnections
Recipe 1.15. Taking Advantage of Connection Pooling
Recipe 1.16. Setting Connection Pooling O ptions
Recipe 1.17. Using Transactions with Pooled Connections
Recipe 1.18. Changing the Database for an Open Connection
Recipe 1.19. Connecting to a Text File
[ Team LiB ]


18 / 442
[ Team LiB ]

Introduction
This chapter describes how to connect to a variety of data sources from ADO .NET; how to handle security-related issues including storing connection s trings and
using different authentic ation methods; and how to set up, monitor, and optimize connection pooling.
ADO.NET Overview

A DO .NET is designed to support data access requirements of loosely coupled n-tier application architectures including web services . A DO .NET can acces s a
variety of different data sources, including relational databases such as Microsoft SQ L Server, Oracle, and Microsoft A cces s, as well as other data sources such as
Microsoft Excel, O utlook, and text files.
A .NET data provider is used to connect to a data source, execute commands, and retrieve results . T he .NET Framework ships with four .NET-managed data
providers: Mic rosoft SQ L Server, Oracle, O LE DB, and O DBC .
O ther providers are also available—for example, O racle has developed its own .NET data provider for Oracle. Data providers also exist for databases such as
Sybase and MySQ L. Databas e-specific providers usually acces s the underlying data store directly and offer the best performance, broadest functionality, and
support for database-specific features. Since a data provider needs only to implement a set of standard interfaces , the capabilities and performance of data
providers for the s ame data source can differ s ignificantly.
In addition to database-specific providers, the O LE DB .NET data provider allows acc ess to most OLE DB data sources through O LE DB providers. Similarly, the
O DBC .NET data provider uses the O DBC drivers to access most ODBC data sources . You can also develop your own data provider to access proprietary data
sources or to meet special requirements.
A DO .NET is fundamentally different from ADO despite sharing a similar name. ADO .NET is based on a disconnected architecture and has both c onnected and
disconnected classes. Each data provider is responsible for providing the connected classes:
Connection
A unique session with the data source.
Command
Executes SQ L statements and stored procedures against the data source.
DataReader
Forward-only, read-only acces s to a query result set stream.
DataAdapter
Bridges the connected classes with the disc onnected classes; also used to fill a disconnected DataSet and update the data source with changes made to a
disconnected DataSet.
The disconnected classes are part of the A DO .NET classes in the .NET Framework. They provide a consistent programming model regardless of the data source or
data provider. The disc onnected classes include:
DataSet
A n in-memory relational database.
DataTable
A single table of memory-resident data.
DataColumn

The schema of a column in a DataTable.
DataRow
A row of data in the DataTable.
DataView
A data-bindable view of a DataTable used for custom sorting, filtering, searching, editing, and navigation.
DataRelation
A parent/child relationship between two DataTable objects in a DataSet.
Constraint
A constraint on one or more c olumns in a DataTable used to maintain data integrity.
The DataSet retains no information about the s ource of the data used to fill it with data. It maintains both current and original versions of data allowing the data
source to be updated with changes at some future time. Disc onnected data classes facilitate transport-independent marshaling vertically between application tiers
and horizontally across a distributed application, and persis ting data.
A DO .NET and XML converge in .NET. You can save the DataSet as an XML document, or fill it from an XML document. You can access and modify data
simultaneously using both the DataSet class es and XML classes.
Connections, Connection Strings, and Connection Pooling
Databas e connections are a critical and limited resource. Connections must be managed to ensure that an applic ation performs well and is scalable. SQL Server and
O racle data providers provide connection pooling while the O LE DB and ODBC providers use the pooling provided by O LE DB or O DBC respectively.
Connections should be opened as late as possible and closed as soon as possible using either the Close( ) or Dispose( ) method. The connection should be used as
briefly as possible, meaning that connections should not last longer than a method call. Connections should not be passed between methods—in addition to creating
performance problems and limiting scalability, this can lead to security vulnerabilities.
Data providers us e a c onnection string containing a collection of attribute/value pairs to establish the c onnection with the database. Recipe 1.1 through Recipe
1.11 show how to connect to different data sources.
Connection s trings need to be stored securely while still being configurable. Recipe 1.12 shows how to use different techniques to store connection strings and
compare them. Recipe 1.13 shows how to use the Data Links Properties dialog box to allow the user to build connection strings at runtime.
SQ L Server supports both SQ L Server authentication and integrated authentication. SQ L Server authentication is easier to program, but not as secure or
manageable as integrated security, which uses Windows authentication to authenticate and authorize data access. Integrated security can be used from A SP.NET
applications, but because the ASP NET account that is used by most ASP.NET applications has limited permissions, it needs to be configured to allow integrated
security to be used from an ASP.NET application. Recipe 1.8 demonstrates this.

19 / 442

Connection pooling allows an applic ation to reuse connections from a pool instead of repeatedly creating and destroying them. This can significantly improve the
performance and scalability of applications by reusing connections and eliminating the overhead of establishing new connections. Recipe 1.15, Recipe 1.16, and
Recipe 1.17 show how to take advantage of connection pooling, how to configure connection pooling with different .NET data providers, and how to use connection
pooling together with transactions.
You can use the SQ L Server Profiler to monitor SQ L Server connections. You can also use the Windows Performance Monitor. .NET also adds Common Language
Runtime (CLR) Data counters to the Window Performance Monitor that you can use to monitor, optimize, and troubleshoot connections in SQ L Server. Recipe 1.14
shows how to monitor c onnections in ADO .NET applications.
.NET data providers implement common interfaces in their class es. You write database-independent c ode by operating on these interfaces rather than on the actual
clas ses. Code becomes more portable but the database-specific functionality available in the provider is usually lost. Recipe 1.11 shows how to develop database-
independent code by using common interfaces.
See About the Code in the Preface for information about the code shown in the solutions.
[ Team LiB ]


20 / 442
[ Team LiB ]

Recipe 1.1 Connecting to an ODBC Data Source
Problem
You want to access your data source using an ODBC provider from your .NET application.
Solution
Us e the ODBC .NET data provider to acc ess data exposed through an O DBC driver.
The sample code contains a single event handler:
Connect Button.Click
Creates an OdbcDataAdapter and uses it to fill a DataTable with the Category table from the Northwind sample database. The default view of the table is bound
to a data grid on the form.
The C # code is shown in Example 1-1.
Example 1-1. F ile: OdbcConnectForm.cs
// Namespaces, variables, and constants
using System;

using System.Configuration;
using System.Data;
using System.Data.Odbc;
// . . .
private void connectButton_Click(object sender, System.EventArgs e)
{
// Create the DataAdapter.
String sqlSelect = "SELECT CategoryID, CategoryName, Description " +
"FROM Categories";
OdbcDataAdapter da = new OdbcDataAdapter(sqlSelect,
ConfigurationSettings.AppSettings["Odbc_ConnectString"]);
// Create the table, fill it, and bind the default view to the grid.
DataTable dt = new DataTable( );
da.Fill(dt);
dataGrid.DataSource = dt.DefaultView;
}
Discussion
The O DBC .NET data provider communicates with native ODBC drivers through CO M interop (.NET's interoperability layer for CO M). The following ODBC providers
are guaranteed to be 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 .NET data provider for O DBC connects to O DBC data sources through the OdbcConnection object. The ODBC driver connection s tring is specified using the
ConnectionString property. It includes settings needed to establish the connection to the data source. T he connection string format c losely matches the O DBC
connection string format. A dditionally, you can specify an O DBC data source name (DSN) or file DSN by setting the ConnectionString attribute to "DSN=myDSN" or
"FileDSN=myFileDSN". For more information about specifying O DBC connection strings, see the topic "SQ LDriverConnect" in the ODBC Programmer's Reference within
MSDN Library.
V isual Studio als o supports creating O DBC data source connections vis ually:
Create a data connection in Server Explorer and drag it onto a form or design surface. C onfigure the OdbcConnection object that appears in the component
tray.

Drag an OdbcConnection from the Data tab of the Toolbox onto a form or design surface. C onfigure the ConnectionString property in the Properties window of the
OdbcConnection object that appears.
The .NET ODBC data provider requires a reference to the System.Data.Odbc namespace in .NET Framework Version 1.1. In Version 1.0, the namespace is
Microsoft.Data.Odbc. Add a .NET Reference to Microsoft.Data.Odbc.dll for a .NET Framework Version 1.0 project.
The .NET ODBC .NET data provider ships with .NET Framework Version 1.1. The data provider can be downloaded from rosoft.c om/downloads for
.NET Framework Version 1.0.
[ Team LiB ]


21 / 442
[ Team LiB ]

Recipe 1.2 Connecting to a Microsoft Excel Workbook
Problem
You want to access data stored in a Microsoft Excel workbook.
Solution
Us e the OLE DB Jet provider to c reate, acc ess, and modify data stored in an Excel workbook.
The sample code contains two event handlers:
Form.Load
Creates an OleDbDataAdapter that uses the Jet OLE DB provider to access an Excel workbook. Custom insert and update logic is created for the DataAdapter.
A DataTable is filled from the first worksheet, Sheet1, in the Excel workbook and the default view of the table is bound to a data grid on the form.
Update Button.Click
Us es the DataAdapter created in the Form.Load event handler to update the Exc el workbook with the programmatic changes.
The C # code is shown in Example 1-2.
Example 1-2. F ile: ExcelF orm.cs
// Namespaces, Variables, and Constants
using System;
using System.Configuration;
using System.Data;
private OleDbDataAdapter da;

private DataTable dt;
// . . .
private void ExcelForm_Load(object sender, System.EventArgs e)
{
// Create the DataAdapter.
da = new OleDbDataAdapter("SELECT * FROM [Sheet1$]",
ConfigurationSettings.AppSettings["Excel_0115_ConnectString"]);
// Create the insert command.
String insertSql = "INSERT INTO [Sheet1$] " +
"(CategoryID, CategoryName, Description) " +
"VALUES (?, ?, ?)";
da.InsertCommand =
new OleDbCommand(insertSql, da.SelectCommand.Connection);
da.InsertCommand.Parameters.Add("@CategoryID", OleDbType.Integer, 0,
"CategoryID");
da.InsertCommand.Parameters.Add("@CategoryName", OleDbType.Char, 15,
"CategoryName");
da.InsertCommand.Parameters.Add("@Description", OleDbType.VarChar, 100,
"Description");
// Create the update command.
String updateSql = "UPDATE [Sheet1$] " +
"SET CategoryName=?, Description=? " +
"WHERE CategoryID=?";
da.UpdateCommand =
new OleDbCommand(updateSql, da.SelectCommand.Connection);
da.UpdateCommand.Parameters.Add("@CategoryName", OleDbType.Char, 15,
"CategoryName");
da.UpdateCommand.Parameters.Add("@Description", OleDbType.VarChar, 100,
"Description");
da.UpdateCommand.Parameters.Add("@CategoryID", OleDbType.Integer, 0,

"CategoryID");
// Fill the table from the Excel spreadsheet.
dt = new DataTable( );
da.Fill(dt);
// Define the primary key.
dt.PrimaryKey = new DataColumn[] {dt.Columns[0]};
// Records can only be inserted using this technique.
dt.DefaultView.AllowDelete = false;
dt.DefaultView.AllowEdit = true;
dt.DefaultView.AllowNew = true;
// Bind the default view of the table to the grid.
dataGrid.DataSource = dt.DefaultView;
}
private void updateButton_Click(object sender, System.EventArgs e)
{
da.Update(dt);
}
Discussion
You can use the Jet OLE DB provider to access Microsoft Excel as a data source. T he Jet database engine can access other database file formats through Indexed
Sequential Acc ess Method (ISA M) drivers specified in the Extended Properties attribute of the connection. Excel 2000 and 2002 are supported with the Excel 8.0
source database type as shown in the following example:

22 / 442
Provider=Microsoft.Jet.OLEDB.4.0;Data Source=myBook.xls;
Extended Properties="Excel 8.0;HDR=YES";
The Extended Properties attribute can, in addition to the ISA M version property, specify whether or not tables include headers as field names in the first row of a
range using an HDR attribute.
There are three ways in whic h you can reference Excel workbook data within a SQ L statement:
Spec ify the worksheet name followed by a dollar sign to acc ess the entire range used in the worksheet:
SELECT * FROM [MySheet$]

Spec ify a range explicitly using cells:
SELECT * FROM [MySheet$A1:E5]
Spec ify a range with a defined name, as shown in the solution:
SELECT * FROM MyRange
The following subsections dis cuss how to use Exc el as an ADO .NET data source.
Create table
The CREATE TABLE c ommand will create a table in an Excel workbook. The workbook for the connection will be created if it does not exist. For example:
CREATE TABLE MySheet (Field1 char(10), Field2 float, Field3 date)
Create data
You can use the INSERT command, either static or parameterized, to insert data into a worksheet or range:
INSERT INTO [MySheet$] (Field1, Field2, Field3)
VALUES ('testdata', 1.234, '09/28/1979');
Retrieve data
Us e either a DataAdapter or a DataReader to retrieve data from an Excel workbook. Create a SQ L SELECT statement referencing a worksheet or a range in an Excel
workbook and execute the statement to fill a DataSet using a DataAdapter or to create a DataReader. For example:
SELECT * FROM [MySheet$]
Update data
The UPDATE command, either static or parameterized, can update data in a worksheet or range. For example:
UPDATE [MySheet$]
SET Field2 = '2.345',
Field3 = '10/18/1964'
WHERE
Field1 = 'testdata'
Delete data
The Jet OLE DB provider does not allow DELETE operations. An error will be raised if an attempt is made to execute a DELETE statement affecting one or more records.
[ Team LiB ]


23 / 442
[ Team LiB ]


Recipe 1.3 Connecting to a Password-Protected Access Database
Problem
You want to connect to a Microsoft A ccess database that has a database password.
Solution
Us e the Jet OLEDB:Database Password attribute in the connection s tring to specify the password.
The sample code contains a single event handler:
Connect Button.Click
Creates and opens a c onnection to a password-s ecured Mic rosoft A c cess database using the O LE DB .NET data provider. Information about the database is
displayed from the properties of the OleDbConnection object.
The C # code is shown in Example 1-3.
Example 1-3. F ile: AccessPasswordForm.cs
// Namespaces, variables, and constants
using System;
using System.Configuration;
using System.Text;
using System.Data;
using System.Data.OleDb;
// . . .
private void connectButton_Click(object sender, System.EventArgs e)
{
StringBuilder result = new StringBuilder( );
// Build the connections string incorporating the password.
String connectionString =
ConfigurationSettings.AppSettings["MsAccess_Secure_ConnectString"]+
"Jet OLEDB:Database Password=" + passwordTextBox.Text + ";";
result.Append("ConnectionString: " + Environment.NewLine +
connectionString + Environment.NewLine + Environment.NewLine);
OleDbConnection conn = new OleDbConnection(connectionString);
try

{
conn.Open( );
// Retrieve some database information.
result.Append(
"Connection State: " + conn.State + Environment.NewLine +
"OLE DB Provider: " + conn.Provider +
Environment.NewLine +
"Server Version: " + conn.ServerVersion +
Environment.NewLine);
conn.Close( );
result.Append("Connection State: " + conn.State);
}
catch(System.Data.OleDb.OleDbException ex)
{
conn.Close( );
result.Append("ERROR: " + ex.Message);
}
resultTextBox.Text = result.ToString( );
}
Discussion
A Microsoft A ccess database password requires that users enter a password to obtain access to the database and database objects. This is also known as share-
level sec urity. A password does not allow groups or users to have distinct levels of acces s or permiss ions. Anyone with the password has unrestricted acces s to the
database.
The Set Database command from the Tools Security menu is used to s et up a database password.
The O LE DB provider for Microsoft Jet has several provider-specific connection string attributes in addition to those defined by ADO .NET. To open a databas e
secured by a Mic rosoft A c c ess database password, use the Jet OLEDB:Database Password attribute in the connection s tring to specify the password. This corresponds
to the O LE DB property DBPROP_JETOLEDB_DATABASEPASSWORD.
A Microsoft A ccess database password does not provide strong security and should only be used as a simple deterrent.
[ Team LiB ]



24 / 442
[ Team LiB ]

Recipe 1.4 Connecting to a Secured Access Database
Problem
You want to connect to a Microsoft A ccess database that has been secured with user-level security and a workgroup file.
Solution
Us e the Jet OLEDB:System Database attribute in the connection string to spec ify the path and filename of the workgroup information file or system database.
The sample code contains a single event handler:
Connect Button.Click
Creates and opens a c onnection to a Microsoft A ccess database secured with user-level security and a workgroup file using the O LE DB .NET data provider.
Information about the databas e is displayed from the properties of the OleDbConnection object.
The C # code is shown in Example 1-4.
Example 1-4. F ile: AccessSecureF orm.cs
// Namespaces, variables, and constants
using System;
using System.Configuration;
using System.Text;
using System.Data.OleDb;
// . . .
private void connectButton_Click(object sender, System.EventArgs e)
{
StringBuilder result = new StringBuilder( );
// Build the connection string with security information.
String connectionString =
ConfigurationSettings.AppSettings["MsAccess_ConnectString"] +
@"Jet OLEDB:System database=" +
ConfigurationSettings.AppSettings["MsAccess_SecureMdw_Filename"] +
";" + "User ID=" + userIdTextBox.Text + ";" +

"Password=" + passwordTextBox.Text + ";" +
Environment.NewLine + Environment.NewLine;
result.Append(connectionString);
// Create the connection.
OleDbConnection conn = new OleDbConnection(connectionString);
try
{
// Attempt to open the connection.
conn.Open( );
result.Append(
"Connection State: " + conn.State + Environment.NewLine +
"OLE DB Provider: " + conn.Provider +
Environment.NewLine +
"Server Version: " + conn.ServerVersion +
Environment.NewLine);
conn.Close( );
result.Append("Connection State: " + conn.State +
Environment.NewLine);
}
catch(System.Data.OleDb.OleDbException ex)
{
result.Append("ERROR: " + ex.Message);
}
resultTextBox.Text = result.ToString( );
}
Discussion
Microsoft Acc ess user-level security requires an additional file—the workgroup information or MDW file—in addition to the database or MDB file. This file contains the
user and group information for the secured database while the actual permissions are stored in the database file.
When you c onnect to a sec ured Jet databas e, the user ID and password are validated against the values in the MDW file. The permissions are obtained from the MDB
file. To connect, the location of both the database file and the workgroup file must be supplied.

The O LE DB provider for Microsoft Jet has several provider-specific connection string attributes in addition to those defined by ADO .NET. To open a databas e
secured by Microsoft A ccess user-level security, use the Jet OLEDB:System Database attribute in the connection string to specify the path and filename of the
workgroup information file or system database. T his corresponds to the OLE DB property DBPROP_JETOLEDB_SYSDBPATH.
[ Team LiB ]


25 / 442

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

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