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

Beginning C# 2005 Databases pdf

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 (6.2 MB, 529 trang )

Beginning
C# 2005 Databases
Karli Watson
44063ffirs.qxd:WroxBeg 9/12/06 3:17 PM Page iii
44063ffirs.qxd:WroxBeg 9/12/06 3:17 PM Page ii
Beginning
C# 2005 Databases
44063ffirs.qxd:WroxBeg 9/12/06 3:17 PM Page i
44063ffirs.qxd:WroxBeg 9/12/06 3:17 PM Page ii
Beginning
C# 2005 Databases
Karli Watson
44063ffirs.qxd:WroxBeg 9/12/06 3:17 PM Page iii
Beginning C# 2005 Databases
Published by
Wiley Publishing, Inc.
10475 Crosspoint Boulevard
Indianapolis, IN 46256
www.wiley.com
Copyright © 2006 by Wiley Publishing, Inc., Indianapolis, Indiana
Published simultaneously in Canada
ISBN-13: 978-0-470-04406-3
ISBN-10: 0-470-04406-3
Manufactured in the United States of America
10 9 8 7 6 5 4 3 2 1
Library of Congress Cataloging-in-Publication Data:
No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or
by any means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permit-
ted under Sections 107 or 108 of the 1976 United States Copyright Act, without either the prior written
permission of the Publisher, or authorization through payment of the appropriate per-copy fee to the


Copyright Clearance Center, 222 Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax (978) 646-8600.
Requests to the Publisher for permission should be addressed to the Legal Department, Wiley Publishing,
Inc., 10475 Crosspoint Blvd., Indianapolis, IN 46256, (317) 572-3447, fax (317) 572-4355, or online at
/>LIMIT OF LIABILITY/DISCLAIMER OF WARRANTY: THE PUBLISHER AND THE AUTHOR
MAKE NO REPRESENTATIONS OR WARRANTIES WITH RESPECT TO THE ACCURACY OR COM-
PLETENESS OF THE CONTENTS OF THIS WORK AND SPECIFICALLY DISCLAIM ALL WAR-
RANTIES, INCLUDING WITHOUT LIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR
PURPOSE. NO WARRANTY MAY BE CREATED OR EXTENDED BY SALES OR PROMOTIONAL
MATERIALS. THE ADVICE AND STRATEGIES CONTAINED HEREIN MAY NOT BE SUITABLE FOR
EVERY SITUATION. THIS WORK IS SOLD WITH THE UNDERSTANDING THAT THE PUBLISHER
IS NOT ENGAGED IN RENDERING LEGAL, ACCOUNTING, OR OTHER PROFESSIONAL SERV-
ICES. IF PROFESSIONAL ASSISTANCE IS REQUIRED, THE SERVICES OF A COMPETENT PROFES-
SIONAL PERSON SHOULD BE SOUGHT. NEITHER THE PUBLISHER NOR THE AUTHOR SHALL
BE LIABLE FOR DAMAGES ARISING HEREFROM. THE FACT THAT AN ORGANIZATION OR
WEBSITE IS REFERRED TO IN THIS WORK AS A CITATION AND/OR A POTENTIAL SOURCE OF
FURTHER INFORMATION DOES NOT MEAN THAT THE AUTHOR OR THE PUBLISHER
ENDORSES THE INFORMATION THE ORGANIZATION OR WEBSITE MAY PROVIDE OR RECOM-
MENDATIONS IT MAY MAKE. FURTHER, READERS SHOULD BE AWARE THAT INTERNET
WEBSITES LISTED IN THIS WORK MAY HAVE CHANGED OR DISAPPEARED BETWEEN WHEN
THIS WORK WAS WRITTEN AND WHEN IT IS READ.
For general information on our other products and services please contact our Customer Care
Department within the United States at (800) 762-2974, outside the United States at (317) 572-3993 or
fax (317) 572-4002.
Trademarks: Wiley, the Wiley logo, Wrox, the Wrox logo, Programmer to Programmer, and related
trade dress are trademarks or registered trademarks of John Wiley & Sons, Inc. and/or its affiliates, in
the United States and other countries, and may not be used without written permission. All other
trademarks are the property of their respective owners. Wiley Publishing, Inc., is not associated with
any product or vendor mentioned in this book.
Wiley also publishes its books in a variety of electronic formats. Some content that appears in print
may not be available in electronic books.

44063ffirs.qxd:WroxBeg 9/12/06 3:17 PM Page iv
for donna
44063ffirs.qxd:WroxBeg 9/12/06 3:17 PM Page v
44063ffirs.qxd:WroxBeg 9/12/06 3:17 PM Page vi
About the Author
Karli Watson is a freelance writer, developer, and editor and also the technical director of 3form Ltd.
(
www.3form.net). He started out with the intention of becoming a world-famous nanotechnologist, so
perhaps one day you might recognize his name as he receives a Nobel Prize. For now, however, Karli’s
main academic interest is the .NET Framework and all the boxes of tricks it contains. Karli is also a
snowboarding enthusiast, loves cooking, spends far too much time playing Anarchy Online, and wishes
he had a cat. As yet, nobody has seen fit to publish Karli’s first novel, but the rejection letters make an
attractive pile. If he ever puts anything up there, you can visit Karli online at
www.karliwatson.com.
44063ffirs.qxd:WroxBeg 9/12/06 3:17 PM Page vii
44063ffirs.qxd:WroxBeg 9/12/06 3:17 PM Page viii
Credits
Acquisitions Editor
Katie Mohr
Development Editor
Maryann Steinhart
Technical Editor
Todd Meister
Additional Material
Donna Watson
Production Editor
Angela Smith
Copy Editor
Nancy Rapoport
Editorial Manager

Mary Beth Wakefield
Production Manager
Tim Tate
Vice President and Executive Group Publisher
Richard Swadley
Vice President and Executive Publisher
Joseph B. Wikert
Compositor
Maureen Forys, Happenstance Type-o-Rama
Proofreading
James Brook
Jennifer Larsen
Word One
Indexing
Johnna VanHoose Dinse
44063ffirs.qxd:WroxBeg 9/12/06 3:17 PM Page ix
44063ffirs.qxd:WroxBeg 9/12/06 3:17 PM Page x
Acknowledgments
Thanks to all at Wiley for helping me through this project and reining in my strange British stylings, to
3form for giving me the time to write, to donna for keeping me sane, Funcom for providing a much-
needed retreat, and to friends and family for being patient with my deadline-laden lifestyle.
44063ffirs.qxd:WroxBeg 9/12/06 3:17 PM Page xi
44063ffirs.qxd:WroxBeg 9/12/06 3:17 PM Page xii
Contents
Acknowledgements xi
Introduction xix
Chapter 1: Database Fundamentals 1
What Is a Database? 2
Relational Database Management Systems 3
Object Oriented Database Management Systems 8

Additional Features of RDBMSes 8
Joins 9
Functions 9
Views 9
Stored Procedures 10
Triggers 10
E-mail 10
Indexes 11
Security 11
Concurrency Control 12
Transactions 13
Remote Access 13
Backups 14
Mirroring and Partitioning 14
Management Tools 14
What RDBMSes Are Available? 15
MySQL and PostgreSQL 15
DB2, Oracle, and SQL Server 16
SQL Server 2005 Express Edition 16
How Do You Use a Database? 17
A SQL Primer 18
XML 30
Summary 33
Exercises 34
44063ftoc.qxd:WroxBeg 9/12/06 3:17 PM Page xiii
xiv
Contents
Chapter 2: Databases and C# 35
Database Access in C# 36
ADO.NET 36

Data Binding 46
Visual Tools 47
Express Products 47
SQL Server Management Studio Express 50
Examples 51
Case Study Introduction 65
Summary 67
Exercises 68
Chapter 3: Viewing Data 69
Creating Data Sources 70
Automatic Data Source Configuration 70
Manual Data Source Configuration 75
Advanced Data Source Configuration 87
Binding to Data Sources 90
The BindingSource Control 91
Binding to List Controls 94
Binding to DataGridView Controls 95
The BindingNavigator Control 102
Adding a Navigable DataGridView in a Single Step 103
Binding to Detail Views 104
Filtering Data 107
Summary 110
Exercises 111
Chapter 4: Modifying Data 113
Data Modification Prerequisites 113
Database Security 114
Database Views 115
Application Data Sources 116
How to Avoid Data Being Overwritten 117
Modifying Data from Data-Bound Controls 119

Adding Rows with GUID Primary Keys 125
How BindingNavigator Saves Data 125
Canceling Updates 125
44063ftoc.qxd:WroxBeg 9/12/06 3:17 PM Page xiv
xv
Contents
Updating Data from Detail Views 126
Updating Multiple Tables 130
Updating Long Text Data for DataGridView Displays 141
Saving Data When the Application Closes 145
Summary 146
Exercises 147
Chapter 5: Databases and the Internet 149
Web versus Windows Applications 150
Data Binding in ASP.NET 151
ASP.NET Data Connections 152
Local Database File Connections 153
Remote Connections 153
ASP.NET Data Source Controls 157
Data Source Configuration 158
Additional Data Source Control Functionality 163
ASP.NET Data Display Control Summary 163
GridView 164
DataList 164
Repeater 165
FormView 166
DetailsView 166
An Introduction to Templates 167
Viewing and Editing Data in List Views 170
Viewing Data 170

Additional Configuration 174
Editing Data 176
Viewing and Editing Data in Detail Views 184
Master/Detail Views 187
Summary 190
Exercises 191
Chapter 6: Accessing Databases Programmatically 193
Database Connections 194
Creating Connections 194
Connection State 196
Connection Pooling 197
Database Commands 197
Creating Commands 197
44063ftoc.qxd:WroxBeg 9/12/06 3:17 PM Page xv
xvi
Contents
Command Types 198
Command Execution Methods 198
Parameterized Commands 200
Protecting Against SQL Injection 201
Data Reader Objects 205
Creating Data Reader Objects 205
Reading Data 206
Connections for Data Reader Objects 210
Data Adapter Objects 212
Configuring Data Adapters 213
Extracting Database Data 218
Modifying Database Data 219
Customizing Data Adapter Behavior 220
DataSet Objects 226

Populating DataSet objects 226
Defining and Using Table Relationships 228
Typed DataSet Classes 232
Summary 239
Exercises 240
Chapter 7: Views and Stored Procedures 241
Database Views 242
Creating Views 243
Updating Data Through Views 254
Stored Procedures 256
Creating Stored Procedures 258
Using Stored Procedures 264
Updating Data Through Stored Procedures 271
Conditional Logic and Looping 272
Cursors 276
Summary 289
Exercises 290
Chapter 8: Custom Data Objects 291
Custom Data Objects 291
n-Tier Application Design Primer 293
Passing Data Reader Objects 294
Using Existing .NET Classes 298
Basic Data-Aware Class Design 303
DataAwareObjects Class Library 304
44063ftoc.qxd:WroxBeg 9/12/06 3:17 PM Page xvi
xvii
Contents
Binding to Object Data 320
Windows Applications 320
Web Applications 323

Summary 332
Exercises 333
Chapter 9: Transactions and Concurrency 335
Concurrency 336
Last in Wins 336
Optimistic Concurrency Management in ADO.NET 339
Concurrency Violations in Client Applications 346
Resolving Concurrency Violations 353
Transactions 358
SQL Transactions 359
.NET Transactions 363
Summary 373
Exercises 374
Chapter 10: Working with Disconnected Data 375
Exposing Web Service Data 376
Web Service Primer 376
Exposing Database Data 383
Consuming Web Service Data 387
Caching Web Service Data 400
Web Method Output Caching 401
Caching Data in Application State 402
Caching Data in the Application Cache 404
Summary 414
Exercises 415
Chapter 11: SQL Server CLR Integration 417
Overview of CLR Integration 418
Enabling CLR Integration 419
Adding Assemblies to SQL Server 420
Requirements of CLR Integration Code 422
Registering CLR Code 422

Common Features of CLR Integrated Code 422
Code Structure 423
Data Access 423
44063ftoc.qxd:WroxBeg 9/12/06 3:17 PM Page xvii
xviii
Contents
Call Context 424
SqlPipe 424
Managed Functions and Stored Procedures 426
Scalar Functions 426
Table-Valued Functions 432
Aggregate Functions 437
Stored Procedures 445
Summary 455
Exercises 456
Appendix A: Installation 457
Appendix B: Database Installation 467
Appendix C: Answers to Exercises 473
Index 483
44063ftoc.qxd:WroxBeg 9/12/06 3:17 PM Page xviii
Introduction
Welcome to Beginning C# 2005 Databases! In this book you learn everything you need to know about
developing C# applications that access databases. If you are wondering why this is such an important
topic, just consider how many applications use the functionality. At first glance, you might notice a few
specialized ones such as Windows applications to view and edit human resources data or Web applica-
tions that display recent sport results. Look a bit deeper, however, and you quickly find that the vast
majority of applications use database data in one form or another, even if it isn’t immediately obvious.
Because you can store pretty much anything in a database, from simple program settings or tables of
related data, through to Web site content, the possibilities are endless. Of course, you might use an alter-
native method for storing data, such as text files, but in almost all cases you get better performance and

more robust applications from a database.
This book is the perfect starting point to learn about databases, and particularly about using Microsoft
SQL Server from .NET 2.0 applications written in C#. Over the course of the book, you learn the funda-
mentals of database technology, how the .NET Framework can be used to access databases, and how to
get the most out of your code. Along the way you are presented with numerous helpful, easy-to-follow
examples that demonstrate the techniques you need. Each example increases your understanding of a
particular subject, and often provides you with tips and tricks that you can adapt to different contexts
in the future. Each chapter also includes exercises to reinforce key concepts, the answers to which are
found at the back of the book. Taken as a whole, there is enough example code for you to see how to
perform a multitude of tasks — from the most simple such as reading data from a database table, to the
more advanced such as writing managed code to run inside SQL Server.
The main idea behind the book is to present you with a solid understanding of the basics of database
access in C#. You’ll also be exposed to many possibilities for future development. You will often learn
about quite complicated techniques, but they are broken into simple steps and carefully explained. These
explanations provide an appreciation for what is possible, and prepare you for handling additional
resources about these subjects when you’ve finished the book. And you’ll be able to do that without fac-
ing instant despair at attempting to learn about a completely new subject because you’ll already know
the basics of what you are doing.
Whom This Book Is For
This book is aimed at people who already have at least a basic understanding of .NET development with
C# and who want to learn about databases and database access. The C# code used in the examples in
this book is described in detail only in cases where it is quite advanced, or where it’s an area you might
not have looked at before. However, no experience with databases is assumed, so the database code you
write (using ADO.NET) is explained from first principles. Databases themselves are explained, as well as
the SQL language used to access them. This book is perfect for you if the word “database” is one that
you’ve heard only in passing.
This book is also appropriate for those who know the basics of database access and already have experi-
ence using SQL and/or ADO.NET. After looking at the basics, you progress to some relatively advanced
44063flast.qxd:WroxBeg 9/12/06 3:45 PM Page xix
programming techniques, so it’s likely that somewhere in this book there’s a topic or two that you

haven’t already learned about. It’s possible that you may require the first few chapters only as a
refresher — if at all — but that isn’t a problem, and should you find out that you’re not quite as comfort-
able with the fundamentals as you thought you were, you have the earlier chapters available as refer-
ence material.
Also, you don’t have to be an employee of a wealthy company or someone who can afford the latest
development tools to get the most out of this book. All of the tools used here are available for free,
including the Microsoft Express developer applications. All you need is a relatively up-to-date computer
and an Internet connection and you can get everything you need. This book is as useful to students as to
full-time developers.
What Does This Book Cover?
This book is divided into four main parts as described in the following sections.
The Fundamentals
Chapters 1 and 2 cover the fundamentals — everything you need to be aware of before you start. In
Chapter 1 you learn exactly what the definition of a database is, the types of database that are available,
and the features that databases provide. Finally, you see how to access databases using the SQL lan-
guage, and take a look at how XML fits into the picture.
In Chapter 2 you move on to learn about ADO.NET, and how it can used to access databases from C#
applications. You’ll also see the Express tools that you’ll be using in this book, and try out a few basic
examples to prepare you for what is to come. This chapter also introduces the sample database used in
this book,
FolktaleDB.
Visual Database Access and Data Binding
Chapters 3–5 provide a look at data-binding techniques you can use to present and modify data in
Windows and Web applications. Using data binding, you can get excellent results while writing little or
no additional code — instead, you use visual tools and declarative techniques to get the behavior you
want. The first two chapters concentrate on Windows applications, starting with a look at reading data-
base data in Chapter 3 and moving on to database modifications in Chapter 4.
Chapter 5 takes what you have learned about database access with ADO.NET and applies it to Web
applications. You’ll see that the details are a little different — particularly with the user interface of Web
applications — but that much of what you’ve learned is, with minor modifications, just as applicable to

Web applications.
Programmatic Database Access
In Chapters 6–8, you start to look at things in a little more depth. You will already know that data bind-
ing is fantastic, but that it doesn’t necessarily cater to everything you might want to do. Sometimes the
only option you have is to write database access code with ADO.NET by hand. In Chapter 6 you see
how to do this, learn about what is possible, and discover how to prevent common problems.
Introduction
xx
44063flast.qxd:WroxBeg 9/12/06 3:45 PM Page xx
In Chapter 7 you explore views and stored procedures in databases and see how you can use them to
simplify the code you need to write in client applications. By performing some of your data manipula-
tion in SQL Server, you won’t have to do it in C# code. However, there are additional things to consider
when you’re working with views and stored procedures, and some tasks require a little more care to
implement correctly. You are provided with plenty of hands-on examples, as well as information about
avoiding trouble.
Chapter 8 looks at writing code to fit into n-tier design principles, particularly how you can abstract data
into custom object families. That gives you greater flexibility in dealing with data, and you will see that
even when you do this, you can still make use of data binding to create database applications quickly
and easily. You’ll also learn how putting a bit more work in at the design phase of application develop-
ment can make your life a lot easier, especially if you work as part of a development team.
Advanced Topics
Chapters 9–11 look at some advanced topics to help you streamline your applications and perform more
complex tasks. You also see how to elude some pitfalls. Chapter 9 examines transactions and concur-
rency, which are critical in multi-user applications because difficulties can arise when more than one per-
son accesses your data simultaneously. You learn how to deal with these situations both by detecting
problems as they arise, and by ensuring that users of your applications are informed about what’s hap-
pening and are permitted to take appropriate action.
In Chapter 10 you look at the more advanced world of distributed application design, focusing on
remote database access across the Internet. You see how to provide Web Services to give you access to
remote data, and how database data can be cached to avoid having too much traffic between Web

servers and database servers.
Finally, in Chapter 11 you’ll look at a topic that’s new to .NET 2.0 and SQL Server 2005: writing managed
code in C# that you can load into and execute inside SQL Server. This enables you to create functions,
stored procedures, and more without resorting to SQL code. You’ll learn how this can give you great
benefits both in ease of development and advanced functionality.
Appendixes
There are three appendixes in this book. Appendix A details the installation procedure required for the
.NET Framework and Express tools used in this book. Appendix B explains how to install the sample
database provided for this book. Appendix C provides the answers for the exercises that are given at the
end of each chapter.
What You Need to Use This Book
You need the following products to use this book:
❑ Microsoft .NET Framework 2.0
❑ Microsoft Visual C# 2005 Express Edition
❑ Microsoft SQL Server 2005 Express Edition
Introduction
xxi
44063flast.qxd:WroxBeg 9/12/06 3:45 PM Page xxi
❑ Microsoft SQL Server Management Studio Express
❑ Microsoft Visual Web Developer 2005 Express Edition
You can find instructions for downloading and installing these products in Appendix A.
Conventions
To help you get the most from the text, a number of conventions are used throughout the book.
Asides to the current discussion are offset and placed in italics like this.
As for styles used in the text:
❑ Important words are highlighted when introduced.
❑ Keyboard combination strokes are presented like this: Ctrl+A.
❑ Filenames, URLs, and code within the text appear in a special monofont typeface, like this:
System.capabilities.
Code blocks and examples appear in two different ways:

In code examples, new code has a gray background.
The gray background is not used for code that is less important in the present
context or that has been shown before.
And in some instances, parts of a code example may be boldface to make it easier for you to spot a
change from earlier code.
Occasionally a code line won’t fit on one line in the book. In those instances, a code continuation charac-
ter (
i
) at the end of a line indicates that the next line is actually a continuation of it.
In text, things you should type into your computer are often shown in bold: Enter the password M3s8halL.
Source Code
As you work through the examples in this book, you may choose either to type in all the code manually,
or use the source code files that accompany this book. All of the source code used in this book is avail-
able for download at
www.wrox.com. Once at the site, simply locate the book’s title (either by using the
Search box or by using one of the title lists) and click the Download Code link on the book’s detail page
to obtain all the source code for the book.
Information of importance outside of the regular text looks like this.
Introduction
xxii
44063flast.qxd:WroxBeg 9/12/06 3:45 PM Page xxii

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

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