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

Tài liệu Programming Microsoft ® SQL Server™ 2000 with Microsoft Visual Basic® .NET pptx

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 (10.6 MB, 530 trang )




Program ming Microsoft® SQL Server™ 2000 with Microsoft Visual
Basic® .NET

Foreword

Acknowledgments

Introduction
Who’s the Book For?
What’s Special About This Book?
How’s the Book Organized?
System Requirem ents
Sam ple Files
Support

1. Getting Started with Visual Basic .NET for SQL Server 2000
Visual Studio .NET, the Visual Basic .NET IDE
An Overview of ADO.NET Capabilities
A Starter ADO.NET Sam ple
Using Query Analyzer

2. Tables and Data Types
Chapter Resources
Data Types for Tables
Scripting Tables

3. Program ming Data Access with T-SQL
Introduction to Data Access with T-SQL


Aggregating and Grouping Rows
Processing Dates
Joins and Subqueries

4. Program ming Views and Stored Procedures
Introduction to Views
Creating and Using Views
Views for Remote and Heterogeneous Sources
Introduction to Stored Procedures
Creating and Using Stored Procedures
Processing St ored Procedure Outputs
Inserting, Updating, and Deleting Rows
Programming Conditional Result Sets

5. Program ming User-Defined Functions and Triggers
Introduction to User-Defined Functions
Creating and I nvoking Scalar UDFs
Creating and I nvoking Table-Valued UDFs
Introduction to Triggers
Creating and Managing Triggers

6. SQL Server 2000 XML Functionality
Overview of XML Support
XML Formats and Schemas
URL Access to SQL Server
Template Access to SQL Server

7. SQL Server 2000 Security
Overview of SQL Server Security
Introduction to Special Security Issues

Sam ples for Logins and Users
Sam ples for Assigning Permissions

8. Overview of the .NET Fram ework
An I ntroduction to the .NET Framework
An Overview of ASP.NET
XML Web Services

9. Creating Windows Applications
Gett ing Started with Windows Form s
Creating and Using Class References
Inheriting Classes
Programming Events
Exception Handling for Run-Time Errors

10. Program ming Windows Solutions with ADO.NET
An Overview of ADO.NET Obj ects
Making Connections
Working with Command and DataReader Objects
DataAdapters , Data Sets, Forms, and Form Controls
Modifying, Inserting, and Deleting Rows

11. Program ming ASP.NET Solutions
Review of ASP.NET Design Issues
Creating and Running ASP.NET Solutions
Session State Managem ent
Data on Web Pages
Validating the Data on a Web Page

12. Managing XML with Visual Basic .NET

SQL Server Web Releases
Overview of XML Technologies
Generating XML Documents with t he .NET Framework
Dynamically Setting an XML Result Set
The Interplay Between XML and Data Sets
Creating HTML Pages with XSLT

13. Creating Solutions with XML Web Services
Overview of Web services
A Web Service t o Ret urn a Comput ed Result
A Web Service t o Ret urn Values from Tables
The SQL Server 2000 Web Services Toolkit
More on Populating Controls with Web Services

About the Author

Forew ord
During m y five years at Microsoft, I ’ve been helping developers understand
technologies such as Microsoft Visual Studio, Microsoft SQL Server, and Microsoft
Office Developer. During the past two years, I have worked on the Microsoft
Office XP Visual Basic Language Reference, and now, the MSDN Office Developer
Center. In the monthly colum n on MSDN, Office Talk, I have written articles to
help Office developers understand the .NET platform and how it affects their
current and future development efforts.
As I write this foreword to Rick Dobson’s book on programming Microsoft SQL
Server solutions with Microsoft Visual Basic .NET, I think back to m y own
experiences developing software applications with Visual Basic. My first
experience with Visual Basic was learning the language using version 3.0. I
rem ember picking up my first Visual Basic beginner’s book and being excited as I
developed my first few “Hello, World” applications. I couldn’t believe how quick

and easy it was to develop software applications that operated sim ilarly to other
popular shareware program s of that tim e.
However, during that tim e I also discovered som e of the shortcom ings of Visual
Basic as an ent erprise-level development language. I t was then that I turned m y
attention to C+ + . I remember being very frustrated at trying to learn the
language, trying to understand concepts such as pointers, memory allocation,
and true object-oriented programm ing. I took classes on C+ + at the local
university, but I got even m ore frustrated having to wait months until I was
taught how to create the sim plest Microsoft Windows form , something I did in
just a couple of m inutes using Visual Basic. In my frustration, I gave up trying to
learn C+ + and have been using Visual Basic to develop software applications ever
since.
As each new version of Visual Basic was released, I readied myself to learn new
software development technologies. First it was ActiveX control development.
Then it was calling the Windows API. Next it was DHTML Applications. Then it was
database developm ent using Microsoft SQL Server. It always seem ed as though I
had to learn a new language and a new development paradigm for every new
technology that cam e along. I kept thinking that there had to be an easier and
more unified approach.
Well, now we’ve reached the advent of the Microsoft .NET platform, and with it, a
revolution in t he Visual Basic language, Microsoft Visual Basic .NET. I believe that
Visual Basic .NET will provide software developers with new opportunities for
quickly and easily designing integrated software applications that connect
businesses and individuals anytime, anywhere, and on virtually any software
device. With advances in the Visual Basic .NET language, Visual Basic .NET
developers will finally be on a par with their C+ + and C# counterparts,
participating in m any high-end development projects. With Visual Studio .NET
features such as cross-language debugging, along with Visual Basic .NET
conformance to the com mon type system and the com mon language runtim e,
organizations can drive down their development costs by tapping into the wide

range of skills that Visual Basic .NET developers now possess.
True object-oriented programming is now available in Visual Basic .NET, including
features such as inheritance and method overloading. I t’s now sim pler to call the
Windows API by using the .NET Fram ework Class Libraries. Web application
development is now as easy as developing Windows form s–based applications.
Database application development is made easier by uniting disparate data object
libraries such as DAO, RDO, OLE DB, and ADO under ADO.NET, ut ilizing the
power of XML to consum e and transmit relational data over computer networks.
And a new technology, XML Web services, allows Visual Basic .NET developers to
host their software applications’ logic over the Web. Additionally, a big issue for
software developers today is that of software application deploym ent and
versioning. I f you don’t agree, j ust ask any software developer about “DLL hell,”
and you’re bound to get an earful. For many .NET applications, the .NET platform
features “copy and paste” or XCOPY deploym ent. (Users simply copy your
application files from the source media to any single directory and run the
application.) And because .NET no longer relies on the registry, virtually all DLL
compatibility issues go away.
With this book, Rick aim s to give you t he skills you need to program SQL Server
solutions with Visual Basic .NET. I know you will find Rick’s book helpful. Rick
brings his experience to bear from three previous books: Programm ing Microsoft
Access Version 2002 (Microsoft Press, 2001), Program m ing Microsoft Access 2000
(Microsoft Press, 1999), and Professional SQL Server Development with Access
2000 (Wrox Press Inc., 2000). Rick also brings his experience of leading a
successful nationwide sem inar tour. More im portant, I know you will enjoy Rick’s
book because of his deep interest in Visual Basic .NET and SQL Server, and in
helping you, the professional developer, understand and apply these technologies
in your daily software application development projects.
Paul Cornell MSDN Office Developer Center
http: / / msdn.microsoft.com/ officeMicrosoft Corporat ion February 2002



Acknow ledgm ent s
This section offers m e a chance to say thank you to all who helped make this
book possible. I wish to offer special recognition to five support resources.
First, the folks at Microsoft Press have been fantastic. Dave Clark, an acquisitions
editor, selected me to write the book just months after I com pleted anot her book
for Microsoft Press. Dick Brown, my project editor, staunchly stood up for his
perception of how to make the book’s organization and content clear to you
without being petty or boring to m e. Dick also lightened my load substantially by
showing a real knack for editing my text without distorting the original intent.
When Dick was especially busy, he handed off some of his load to Jean Ross, who
also did an admirable job. Others at Microsoft Press who contributed to my well-
being in one way or another include Aaron Lavin and Anne Hamilton.
Second, I had excellent working relations with several professionals within
Microsoft. Paul Cornell, a widely known technical editor at Microsoft, was kind
enough to share his insights on how to present .NET concepts com pellingly. I
want to thank Paul especially for writ ing the Foreword to this book. Karthik
Ravindran served as the MSXML Beta Product Lead Engineer at Microsoft Product
Support Services during the t im e that I wrote this book. He provided valuable
technical content about the SQL Server 2000 Web releases. Other Microsoft
representatives providing moral and technical support for this book include
Richard Waym ire and Jan Shanahan.
Third, I want to express my appreciation to the many readers, sem inar
attendees, and site visitors who took the time to tell m e what I did right or wrong
for them, and also to those who shared their technical support questions with m e.
It is through this kind of feedback that I am able to know what’s important to
practicing developers. I encourage you to visit my m ain Web site
(http: / / www.program mingmsaccess.com) and sign the guest book. The entry
form includes space for you to leave your evaluation of this book or your question
about a topic covered in the book. I prom ise to do my best to reply personally. I n

any event, I definitely read all m essages and use them so that I can serve you
better with future edit ions of this, and other, books.
Fourth, I want t o tell the world how grateful I am to my wife, Virginia. Without
Virginia’s warm support, love, and care, this book would be less professional. She
relieves me of nearly every responsibility around the house when I undertake a
book project. In addition, she offers strategic advice on the issues to address and
their style of coverage. When I run out of tim e, she even pitches in with the
proofreading.
Fifth, it is important for me to give praise and glory to my Lord and Savior, Jesus
Christ, who I believe gave me the strengt h and wisdom to write this book. I n
addition, He gave me health during the long gestation period that resulted in the
birth of this book. It is my prayer that the book prove to be a blessing to you.


I ntroduct ion
Anyone who buys a book—or considers buying it—wants to know who the book is
for, what sets it apart from others like it, and how the book is organized. This
introduction covers those three questions, and it also discusses system
requirem ents, sample files, and support.
• First , w ho is the book for? There are at least two answers to t his
question. One answer is that the book targets professional developers
(and others aspiring to be professional developers). The second group the
book addresses is those w ho want to build full- featured, secure SQL
Server solutions with Visual Basic .NET.
• Second, w hat’s special a bout t h e book? I hope you com e to believe
that the m ost important answer to this question is that the book
considered quality and depth of coverage m ore im portant than rushing to
m arket. The book will arrive on bookshelves more than three months after
the official release of the .NET Framework. It is my wish that you derive
value from the extra tim e taken to develop the many code samples and

the in-depth discussions of advanced topics, such as class inheritance,
ASP.NET, and XML Web services.
• Th ird, h ow is the b ook organiz e d? The short answer is that there are
two main sections. One section introduces SQL Server concepts as it
dem onstrates T- SQL (Transact SQL) program ming techniques. After
conveying SQL Server basic building blocks in the first part, the second
part reveals how t o put those parts together with Visual Basic .NET and
related t echnologies into SQL Server solutions for handling com mon
database chores.
The three support item s include a brief description of the book’s companion CD
and how to use it, Microsoft Press Support Information for this book, and a
summ ary of system and software requirem ents for the sam ple code presented in
the book.


W ho’s t he Book For ?
This book targets professional Visual Basic and Visual Basic for Applications
developers. From my seminar tours and Web sites
(http: / / www.program mingmsaccess.com and http: / / www.cabinc.net), I know
that these professionals are driven by a passion to deliver solutions to their
clients through applying the most innovative technologies their clients will accept.
In-house developers are the go-to persons for getting results fast— particularly for
custom in-house systems and databases. I ndependent developers specialize in
serving niche situations that can include under-served business needs and work
overflows. I n both cases, these professionals need training materials that address
practical business requirem ents while showcasing innovative technologies without
wasting their tim e. This book strives to serve this broad need in two specific
areas.
This book is for developers looking for code sam ples and step-by-step instructions
for building SQL Server 2000 solutions with Visual Basic .NET. The book focuses

on the integration of SQL Server 2000 with .NET technologies tapped via Visual
Basic .NET. It is my firm belief that you cannot create great SQL Server solutions
in any programming language without knowing SQL Server. Therefore, this book
goes beyond t raditional coverage of SQL Server for Visual Basic developers. You’ll
learn T-SQL program ming techniques for data access, data manipulation, and
data definition. A whole chapter equips you to secure your SQL Server solutions.
In addition, there’s plenty of content in this book on Visual Basic .NET and relat ed
technologies, such as ADO.NET, ASP.NET, XML (Extensible Markup Language),
and XML Web services. The presentation of t hese technologies demonstrates
coding techniques and explores concepts that equip you to build better solutions
with SQL Server 2000 databases. I n addition, the book highlights innovations
introduced through the Web releases for SQL Server 2000 that integrate SQL
Server 2000 tightly with Visual Basic .NET.
This isn’t a book about XML, but three of t he book’s 13 chapters focus in whole or
in part on XML. Therefore, those seeking practical dem onstrations of how to use
XML wit h SQL Server and Visual Basic .NET will derive value from this book. I f
you have looked at any of the com puter magazines over the past couple of years,
you know that XML is coming to a solution near you. However, the rapid pace of
XML innovat ion may have dissuaded some from jumping on the bandwagon while
they wait to see what’s going to last and what’s just a fad. I n the book’s three
chapters on XML technology, you’ll learn about XML documents, fragments, and
formatting as well as related technologies, such as XPath (XML Path Language)
queries, XSLT (Extensible Stylesheet Language Transform ation), and WSDL (Web
Services Description Language).


W hat ’s Special About This Book?
There are several features that make this book stand apart from the flood of
books on .NET. One of the m ost im portant of these is that this book didn’t rush to
market but rather shipped m onths after t he release of the .NET Framework. This

allowed me enough time to filter, exam ine, and uncover what were the most
useful and innovative features for Visual Basic .NET developers building SQL
Server solutions. For exam ple, the book includes a whole chapter on creating
solutions with XML Web services. That chapter includes two major sections on the
SQL Server 2000 Web Services Toolkit, which didn’t ship until the day of the .NET
Framework release.
The .NET Fram ework content is at a professional level, but it isn’t just for techies.
This book doesn’t assume any prior knowledge of the .NET Framework. I t does
assume that you get paid for building solutions programmatically and that at least
some of those solutions are for SQL Server databases. Therefore, the book
explains basic .NET concepts and dem onstrates how to achieve practical results
with those concepts through a huge collection of .NET code samples.
This book is about building solutions for SQL Server 2000. I include coverage of
the many special feat ures that tie Visual Basic .NET and SQL Server 2000 closely
to one another. Although there is coverage of general .NET database techniques,
this book dives deeply into T-SQL programming techniques so that you can create
your own custom database objects, such as tables, stored procedures, views,
triggers, and user-defined functions. I n addition, there is separate coverage of
the XML features released wit h SQL Server 2000 as well as separat e coverage of
the XML features in the first three Web releases that shipped for SQL Server
2000. There are numerous code sam ples throughout t he book. These will equip
you to build solutions with Visual Basic .NET, T-SQL, and combinations of the two.
Finally, this book is special because of the unique experiences of its author, Rick
Dobson. I have trained professional developers in Australia, England, Canada,
and throughout the United States. This is my fourth book in four years, and you
can find my articles in popular publications and Web sites, such as SQL Server
Magazine and MSDN Online. As a Webmaster, m y main site
(http: / / www.program mingmsaccess.com) serves hundreds of thousands of
sessions to developers each year. I constantly examine their viewing habits at the
site to determine what interests them. In addition, m y site features scores of

answers to technical support questions subm itted by professional developers. My
goal in offering answers to these questions is to stay in touch with practicing
developers worldwide so that my new books address the needs of practicing,
professional developers.


How ’s the Book Organized?
There are two main parts to this book tied together by an introductory part. Part
II , the first main part, dwells on SQL Server techniques. Part II I builds on the
SQL Server background as it lays a firm foundation in .NET techniques for Visual
Basic .NET developers. Part I, the introductory part, demonstrates ways to use
SQL Server and Visual Basic .NET together.
Part I , I nt roduct ion
Part I, which includes only Chapter 1, has three main goals. First, it acquaints you
with the basics of Visual Basic .NET within Visual Studio .NET. You can think of
Visual Basic .NET as a major upgrade to the Visual Basic 5 or 6 that you are
probably using currently. This first section introduces som e concepts that you will
find useful as you initially learn the landscape of Visual Basic .NET. The second
goal of Chapter 1 is to introduce ADO.NET. If you think of Visual Basic .NET as a
major upgrade to Visual Basic 6, ADO.NET is more like a major overhaul of ADO.
In two sections, you get an introduction to ADO.NET classes— particularly as they
relate to SQL Server— and you get a chance to see a couple of beginner sam ples
of how to create SQL Server solutions with Visual Basic .NET and ADO.NET. The
third goal of the introductory part is to expose you to Query Analyzer. This is a
SQL Server client tool that ships with all commercial editions of SQL Server 2000.
You can think of it as an I DE for T-SQL code. Most of the book’s first part relies
heavily on T-SQL, and therefore having a convenient environment for debugging
and running T-SQL code is helpful. The final section of Chapter 1 addresses this
goal.
Part I I , SQL Ser ver

Part II consists of six relatively short chapters that focus substantially on
programming SQL Server 2000 with T-SQL. Chapter 2 and Chapter 3 introduce T-
SQL and SQL Server data types. I f you are going to program SQL Server and
create efficient, fast solutions, you m ust learn SQL Server data types, which is
one of t he main points conveyed by Chapter 2. Many readers will gravitate to
Chapter 3 because it introduces core T-SQL program ming techniques for data
access. You’ll apply the techniques covered in this chapter often as you select
subsets of rows and columns in data sources, group and aggregate rows from a
table, process dates, and join data from two or more tables. Chapter 3 also
considers special data access topics, such as outer joins, self joins and
subqueries.
The next pair of chapters in Part II, Chapter 4 and Chapter 5, take a look at
programming database objects t hat you will use for data access and dat a
manipulation, such as views, stored procedures, user-defined functions, and
triggers. These database objects are important for many reasons, but one of the
most important is that they bundle T-SQL statements for their easy reuse. I t is
widely known that the best code is the code that you don’t have to write.
However, if you do have to write code, you should definitely write it just onc, and
then reuse it whenever you need its functionality. Stored procedures are
particularly desirable database obj ects because they save com piled T-SQL
statements that can deliver significant speed advantages over resubm it ting the
same T-SQL statem ent for compilation each time you want to perform a data
access or data manipulation task. Chapter 4 and Chapter 5 are also important
because they convey T-SQL syntax for using param eters and conditional logic
that support dynamic run-tim e behavior and user interactivity.
One of the most important features of SQL Server 2000 is its XML functionality.
Because XML as a topic is changing so rapidly, Microsoft adopted a strategy of
upgrading the SQL Server 2000 XML functionality through Web releases. Although
those with SQL Server 2000 can download the Web releases without charge from
the Microsoft Web site, the Web releases are fully supported. Chapter 6

introduces core XML functionality introduced with SQL Server 2000 as well as
functionality from the first two Web releases. I n particular, you can learn in this
chapter about I IS virtual directories as well as formats for XML documents and
schemas. You also learn about tem plates in virtual directories that facilitate data
access and data manipulation tasks over the Web.
Chapter 7 closes out the SQL Server part of t he book with an in-depth look at
programming SQL Server security. I n these tim es, security has grown into a
monumental topic, and this chapter can keep you out of trouble by blocking
hackers from getting into or corrupting your database. You learn such t opics as
how to create and manage different types of login and user accounts and how to
control the permissions available to individual accounts as well as groups of
accounts. By learning how to script accounts and permissions with T-SQL, you
simplify revising and updating security as conditions change (for exam ple, when
users leave the company or when new, sensitive data gets added to a table).
Part I I I , .NET
Chapter 8 starts the .NET part of the book with a review of selected .NET topics
that are covered in the initial look Chapter 1 offered at the .NET Framework. This
chapter provides an overview of the architecture for .NET solutions, and it drills
down on two topics: ASP.NET and XML Web services. The general purpose of this
chapter is the sam e as Chapter 1, which is to introduce concepts. The em phasis
in Chapter 8 isn’t how you do som ething, but rather what are the m aj or
technologies enabling you to do som ething. Chapter 1 and Chapter 8 are both
relatively short chapters, but you m ay find t hem invaluable if you are the kind of
person who benefits from high-level overviews of a collection of topics.
Chapter 9 starts with a close exam ination of how to use Windows Form s with
Visual Basic .NET. It then shifts its focus to a review of traditional class
processing concepts via Visual Basic .NET as an introduction to class inheritance,
a new object-oriented feature that makes its first appearance in Visual Basic with
Visual Basic .NET. Next the treatment of classes progresses to the handling of
built-in events as well as the raising of custom events. Finally the chapter closes

with an exam ination of the new exception handling techniques for processing run-
time errors.
Chapter 10 is a how-to guide for solutions to typical problems with ADO.NET.
Before launching into its progression of sam ples showing how to perform all kinds
of tasks, the chapter starts with an overview of the ADO.NET object model that
covers the main objects along with selected properties and methods for each
object. The how-t o guide focuses on data access tasks, such as selecting rows
and columns from SQL Server database objects, as well as data m anipulation
tasks, such as inserting, updating, and deleting rows in a table. Working through
the samples in the how-to guide offers a hands-on feel for using the
Syst em .Dat a.SqlClient namespace elem ents to perform typical tasks.
Chapter 11 switches the focus to the Web by addressing the creation and use of
ASP.NET solutions. This chapter starts by introducing basic elem ents that you
need to know in order to use ASP.NET to create great Web solutions with Visual
Basic .NET. These include learning what happens as a page does a round-trip
from a browser to a Web server and back to the browser— particularly for data
associated with the page. Other preliminary topics that equip you for building
professional Web solutions include running the same page in multiple browser
types and sniffing the browser for cases in which you want to send a page
optim ized for a specific kind of browser type. Managem ent of session state is a
major topic in the chapter, and you learn how t o use enhancem ents to Session
variables for Web farms as well as the new view state variables, a non-server-
based technique for managing state in ASP.NET solut ions. The last two sections in
the chapter deal with ADO.NET topics in ASP.NET solut ions and the new
autom at ic data validation features built right into ASP.NET.
The last two chapters in the book explore how XML interplays with Visual Studio
.NET and SQL Server 2000. For example, Chapter 12 exam ines special tools in
Visual Studio .NET to facilitate the design and editing of XML document s and
schemas. I n addition, you learn how to designate XPath queries that accept run-
time input for returning SQL Server result sets inside Visual Basic .NET programs.

The chapter demonstrates techniques for processing the XML document
associated with all ADO.NET data set objects. I n the chapter’s last section, I
present a couple of code sam ples that illustrate how to program static HTML
pages based on XML docum ents with XSLT.
Chapter 1 3 drills down on XML Web services by dem onstrating several different
approaches for creating Web services as well as consuming XML output from Web
services. Web services behave som ewhat like COM objects in that you can set up
server applications for client applications. The server applications expose methods
to which the client applications can pass param eters. XML com es int o play with
Web services in a couple of areas. First, Web services represent t heir inputs and
outputs via WSDL, an XML-based language that formally describes an XML Web
service. Second, Web services return data to their clients as XML documents or
document fragments.


System Requirem ents
The requirem ents for this book vary by chapter. I developed and tested all
samples throughout this book on a com puter equipped with Windows 2000
Server, SQL Server Enterprise Edition, and the Enterprise Developer Edition of
Visual Studio .NET, which includes Visual Basic .NET. To use this book, you’ll need
to have Visual Basic .NET or Visual Studio .NET installed on your com puter. (See
Chapter 1 for m ore inform ation on versions of Visual Basic .NET and Visual Studio
.NET.) I n addition, you’ll need SQL Server 2000, and for some of the chapters,
you’ll need SQL Server 2000 updated with Web releases 1, 2, and 3. Chapter 6
gives the URLs for downloading Web releases 1 and 2. Chapter 12 gives two
different URLs for downloading Web Release 3— one with the SQL Server 2000
Web Services Toolkit and the ot her without it.
For selected chapters, you can run the samples with less software or different
operating systems than the one that I used. For exam ple, chapters 2 through 5
will run on any operating system that supports a commercial version of SQL

Server 2000, such as Windows 98 or a more recent Windows operating system.
Chapter 7 requires an operating system that supports Windows NT security, such
as Windows 2000 or Windows XP Professional. Chapter 6, Chapter 11, and
Chapter 1 3 require Microsoft Internet Information Services (II S). I n addit ion,
Chapter 6 requires the installat ion of Web releases 1 and 2. For Chapter 11, your
system needs to meet the minimum requirem ents for ASP.NET. (See a note in the
“How Does ASP.NET Relate to ASP?” section of Chapter 8.) Several of t he
samples in Ch apt er 13 require Web Release 3 and its associated SQL Server
2000 Web Services Toolkit.


Sa m ple Files
Sample files for this book can be found at the Microsoft Press Web sit e, at
http: / / www.microsoft.com /mspress/ books/ 5792.asp. Clicking the Com panion
Content link takes you to a page from which you can download the sam ples.
Supplem ental content files for this book can also be found on the book’s
companion CD. To access those files, insert the com panion CD into your
computer’s CD-ROM drive and make a selection from the menu that appears. I f
the AutoRun feature isn’t enabled on your system (if a menu doesn’t appear when
you insert the disc in your com puter’s CD-ROM drive), run StartCD.exe in the root
folder of the com panion CD. I nstalling the sample files on your hard disk requires
approxim ately 15.3 MB of disk space. I f you have trouble running any of these
files, refer to the text in the book that describes these programs.
Aside from the sam ple files that this book discusses, the book’s supplem ental
content includes a stand-alone eBook installation that will allow you to access an
electronic version of the print book directly from your desktop.


Support
Every effort has been made to ensure the accuracy of this book and t he contents

of the companion CD. Microsoft Press provides corrections for books through the
World Wide Web at the following address:
http: / / www.microsoft.com /mspress/ support
To connect directly to the Microsoft Press Knowledge Base and enter a query
regarding a question or an issue that you may have, go to:
http: / / www.microsoft.com /mspress/ support/ search.asp
If you have comments, questions, or ideas regarding t his book or the com panion
content, or questions that are not answered by querying the Knowledge Base,
please send them to Microsoft Press via e-mail to:
mspinput@m icrosoft.com
Or via postal mail to:
Microsoft Press Attn: Programm ing Microsoft SQL Server 2000 w it h Microsoft
Visual Basic .NET Editor One Microsoft Way Redmond, WA 98052-6399
Please note that product support is not offered through the above m ail address.
For product support information, please visit the Microsoft Support Web site at:
http: / / support.microsoft.com


Chapter 1 . Get t ing St a rt e d w ith Visua l
Basic .NET for SQL Se rver 2 0 0 0
This book aims t o give professional developers the background that they need to
program SQL Server applications with Microsoft Visual Basic .NET. This overall
goal implies three guidelines:
• First, the book targets practicing developers. In my experience, these are
busy professionals who need the details fast. These individuals already
know how to build applications. They buy a book to learn how t o build
those applications with a specific set of tools.
• Second, the book is about building applications for SQL Server 2000. This
focus justifies in-depth coverage of SQL Server program ming topics— in
particular, T-SQL, Microsoft’s extension of the Structured Query Language

(SQL).
• Third, the book illustrates how to program in Visual Basic .NET, but with
particular emphasis on database issues for SQL Server 2000. Special
attention goes to related .NET technologies, such as the .NET Fram ework,
ADO.NET, ASP.NET, and XML Web services.
My goal in this chapter is to equip you conceptually for the rest of the book.
Therefore, this chapter includes material that acquaints you with application
development techniques and topics for SQL Server 2000 and Visual Basic .NET.
The discussion of the sam ples in this chapter generally aims to convey broad
approaches instead of how to run t he sample. All the rem aining chapters except
for Chapter 8, anot her conceptual chapter, have sam ples with instructions aimed
at professional developers.
I believe that the overwhelming majority of professional Visual Basic developers
have no hands-on fam iliarity with Visual Basic .NET and its related technologies.
If you already knew Visual Basic .NET, it wouldn’t m ake any sense to buy a book
describing how to use it. This chapter therefore focuses on how to get started
with Visual Basic .NET and one of its core related technologies for those building
SQL Server applications— ADO.NET. I also believe t hat most Visual Basic
developers don’t have an intimate knowledge of SQL Server— especially for
creating user-defined objects, such as tables, views, and stored procedures. This
capability can empower you to build m ore powerful and more secure applications.
As you learn about database objects and how to create them in Chapter 2
through Chapt er 7, reflect back on the Visual Basic .NET coverage in this chapter
and how to marry database creation techniques and Visual Basic .NET
development techniques. One of the best tools to build database objects is SQL
Server 2000 Query Analyzer. This chapter’s closing section conveys the basics of
Query Analyzer t hat you need to follow the sam ples in Chapter 2 through Chapter
7.



Visua l St udio .NET, t he Visual Basic .NET I DE
Visual Studio .NET is the new multilanguage integrated development environment
(IDE) for Visual Basic, C# , C+ + , and JScript developers. I f you are developing
solutions for Visual Basic .NET, I definitely recommend that you use Visual Studio
.NET as your development environment. This section demonstrates how to get
started using Visual Studio .NET for developing solutions with Visual Basic .NET.
Visual Basic .NET is available as part of Visual Studio .NET in four edit ions:
• Professional
• Enterprise Developer
• Enterprise Architect
• Academ ic
All four edit ions of Visual Studio .NET include Visual Basic .NET, Microsoft Visual
C# .NET, Microsoft Visual C+ + .NET, and support for other languages. In
addition, Microsoft offers Visual Basic .NET Standard, which doesn’t include Visual
C# .NET or Visual C+ + .NET.
Because this book targets professional Visual Basic developers creating SQL
Server applications, it uses the Enterprise Developer Edition of Visual Studio
.NET. You m ay notice some differences if you’re using another edition.
Visual Studio .NET can be installed on computers running one of five operating
systems: Windows 2000, Windows NT, Windows XP, Windows ME, and Windows
98. Not all the .NET Fram ework features are available for each operating system .
For exam ple, Windows 98, Windows Me, and Windows NT don’t support
developing ASP.NET Web applications or XML Web services applications. The
samples for this book are tested on a computer running Windows 2000 Server,
which does support all .NET Fram ework features.
St art ing Visua l St udio .NET
To open Visual Studio .NET, click t he Start button on the Windows taskbar,
choose Programs, and then choose Microsoft Visual Studio .NET. Visual Studio
displays its integrated development environment, including the Start Page (unless
you previously configured Visual Studio to open differently). From the Start Page,

you can configure Visual Studio to work according to your development
preferences, and you can start new solutions as well as open existing projects.
Configu ring Visua l St udio .NET for Visua l Ba sic .NET
Use the links on the left side of the Start Page to begin configuring Visual Studio
.NET for developing solutions in Visual Basic .NET. Click the My Profile link to
open a pane in which you can specify an overall profile as well as individually
indicate your preferences for Keyboard Scheme, Window Layout, and Help Filter.
You also can designate the initial page that Visual Basic .NET displays. When you
are beginning, it m ay be particularly convenient to choose Show Start Page. As a
Visual Basic developer who has worked with Visual Basic 6, you might feel most
familiar with a layout that reflects your prior development environment. Figure 1-
1 shows these My Profile selections.
Figu re 1 - 1. My Profile sele ct ions for starting V isu al St udio .N ET for a
Visual Ba sic de velop e r.

Using t he St art Page
After setting your profile, you can return to the initial Start Page pane by
choosing the Get Started link from t he menu on the left border. I f you had
created previous solutions, the last four modified projects would appear on the
Proj ects tab of the Start Page. The tab shows project names along with date last
modified. I f a project you want to view doesn’t appear on the list, you can click
the Open Project link to display the Open Project dialog box and then navigate to
a directory containing the previously created solution. Select the project’s folder
that you want to open in the IDE, and double-click the solution file (.sln) for the
project. The next section illustrates this process in the context of a sample
project.
To create a new solution, click the New Project link to open the New Project
dialog box. I f you saved preferences such as those shown in Figure 1-1, the
dialog will automatically select Visual Basic Projects in the Project Types pane of
the New Project dialog box. On the right, you can select a template for launching

a project. Table 1-1 shows the project template nam es along with a brief
description available from the Enterprise Developer Edit ion of Visual Studio .NET.
Choosing a template (by clicking OK after selecting a template) opens a project
ready for creating the t ype of solution that you want to develop. When Visual
Studio .NET saves the template to start a new project, it specifies either a file
folder or a Web site for the template’s files; you can override the default nam es
for the file folder and Web site.
N ote
Not all the project template types in Table 1-1 are available
with the non-Enterprise (or Standard) editions of Visual
Studio .NET. In addition to the em pty projects, the Standard
editions make available the Windows Application, ASP.NET
Web Application, ASP.NET Web Service, and Console
Application templates.
7DEOH9LVXDO%DVLF1(73URMHFW7HPSODWH7\SHV
7HPSODWH1DPH &UHDWHV$
Windows
Application
Windows application with a form
Class Library
Windows application suitable for a library of classes without a
form
Windows Control
Library
Project for developing custom reusable form controls for
Windows applications
ASP.NET Web
Application
Web application on a Web server
ASP.NET Web

Service
XML Web service on a Web server
Web Control Library

Project for developing custom reusable controls for Web
applications
Console Application

Comm and line application that operates in an MS- DOS–style
window (the Console)
Windows Service Windows service, formerly NT service, application that runs
in the background without its own custom user interface
Em pty Project Local project with no custom style
Em pty Web Project Web project with no custom style
New Project In
Existing Folder
Blank project in an existing folder
There are two main categories of tem plates: Web projects and local proj ects. Web
projects permit a browser to serve as the client for a proj ect. Web proj ects are
optim ized for form processing on the Web server. Local projects offer custom
form user interfaces with the capability of processing on a local workstation. Local
projects can provide richer environments more conducive to client-side
programming, but local projects don’t offer the wide accessibility of solutions
running from a Web server.
Crea ting a nd Running a Console Application
When you select a Console Application tem plate and click OK t o launch a new
project, Visual Studio .NET responds by opening a project with a blank module. In
addition to the Module window, Visual Studio displays Solution Explorer and the
Properties window. You can enter code directly into the Module window, which
appears as a tab that you can select alternately with the Start Page. Figure 1-2

shows a code sam ple in the Main subroutine that prom pts for a first and second
name before com bining them and displaying them in t he Console (the computer’s
monitor). The code is also available as MyNam eI sFrom Console in the Chapter 1
folder on the companion CD for this book. Although Visual Basic developers didn’t
previously have Console applications routinely available, t his sample should be
very easy to follow. The final two lines present an instruction and cause the
window to rem ain open until the user responds to the instruction. This allows the
user to view the full name in the Console window.
Figu r e 1 - 2. A Console a p plica t ion for displayin g a full nam e based on u ser
input for first and second nam es.

To the right of the Module window are two other windows. The top one of these is
Solution Explorer. I t shows the file structure for the solution. Solution Explorer
indicates in its first line that the solution consist s of just one proj ect. Below that
line appears the nam e of the proj ect, MyNameI sFromConsole. Within the proj ect
are three entries: one each for the References, AssemblyInfo.vb, and Module1.vb
elem ents within the solution’s project. By default, the Properties window is below
Solution Explorer. I n the Full Pat h property text box is an excerpt showing t he
path to Module1.vb on my com puter. When you click the project name in Solution
Explorer, the Project Folder text box in t he Properties window displays the path of
the directory holding the solution’s files. I t is this directory that you copy to
deploy your solution on another computer with the .NET Fram ework installed. The
solution won’t run without the com mon language runtime on the computer to
which you copy the directory containing the .NET Fram ework solution. See
Chapter 8 for m ore detailed coverage of the .NET Fram ework, including the
runtime and distributing .NET Fram ework solutions as assem blies of files in
folders.
You can test run the application by choosing Start from the Debug m enu, or by
pressing F5. This opens the Console window with a prompt to enter a first nam e.
After you close your application and save any changes to it, your solution appears

on the Start Page for recent solutions. I f you start Visual Studio .NET and the
solution you want to open doesn’t appear on the Proj ects tab of the Start Page,
you can also open the solution by clicking Open Project. I n the Open Project
dialog box, choose the file with t he .sln extension and the solution’s name
(MyNameIsFromConsole). A solution can contain just one .sln file, but it can
contain multiple projects.
You also can run t he solution and open the Console window directly from
Windows Explorer without using Visual Studio .NET. Open the bin subdirectory
within the directory containing the assembly folder for the solution. Then double-
click the MyNameI sFrom Console.exe file. This opens the Console window with the
prompt for a first name.


An Overview of AD O.NET Ca pabilit ies
ADO.NET encapsulates the data access and data manipulation for the .NET
Framework. This section gives you an overview of the topic that equips you for a
starter sample in the next section. Microsoft chose the nam e ADO.NET for the
.NET Framework data access com ponent t o indicate its association with the earlier
ADO technology for data access. While there are som e sim ilarities in syntax
between ADO.NET and ADO (particularly for connection strings), many will find
the differences are more obvious than t he sim ilarities. These differences
substantially upgrade ADO.NET over ADO in two key areas— scalability and XML
(Extensible Markup Language) interoperability. As a result, you will be able to
create database applications with ADO.NET that serve more users and share m ore
data than you did with ADO. See Chapter 10 for a more intensive examination of
ADO.NET. Chapter 12 explicitly explores interoperability between ADO.NET and
XML.
.NET Data Provide r Types
Your .NET Framework solutions require .NET data providers to connect to data
sources. These providers are different from those used wit h ADO, but there are

distinct sim ilarities in some of the ways you use them. With .NET data providers,
your solutions can connect, read, and execute com mands against data sources.
The .NET providers also offer selected other functions, such as the management
of input and output param eters, security, transactions, and database server
errors.
Visual Studio .NET ships with two .NET data providers— the SQL Server .NET data
provider and the OLE DB .NET data provider. I n addition, you can download an
ODBC .NET data provider from the Microsoft MSDN download site
(http: / / msdn.microsoft.com /downloads/ default.asp).
N ote
As I write this chapter, the ODBC .NET data provider just became
available with the rollout of the shipping version of Visual Studio
.NET. You can download it from
http: / / m sdn.microsoft.com/ downloads/ default.asp?url= / downloads/ s
ample.asp?url= / msdn-files/ 027/001/ 668/ msdncompositedoc.xml.
The URLs for resources sometimes change. You can always search
for the ODBC .NET data provider at the MSDN download site to
obtain its current download location.
The three providers taken together offer fast, highly focused access to selected
data sources as well as general access to a wide range of possible data sources.
The SQL Server .NET data provider is optim ized for SQL Server 7.0 and SQL
Server 2000. This data provider connects directly to a SQL Server instance.
The OLE DB .NET data provider connects to OLE DB data sources through two
intermediat e layers— the OLE DB Service Component and the classic OLE DB
provider introduced along with ADO. The OLE DB Service Component m anages
connection pooling and transaction services. The classic OLE DB provider, in turn,
directly connects to a database server. Microsoft explicitly tested the OLE DB .NET
data provider with SQL Server, Oracle, and Jet 4.0 databases. Use the OLE DB
.NET data provider to connect to the SQL Server 6.5 version and earlier ones.
This provider is also good for connecting to your Microsoft Access solutions based

on the Jet 4.0 engine.
The OLE DB .NET data provider definit ely doesn’t work with the OLE DB provider
for ODBC data sources (MSDASQL). Because the .NET OLE DB data provider
doesn’t connect to ODBC data sources, you require the ODBC .NET data provider
for connecting to ODBC data sources from your .NET Framework solutions.
There are four main .NET data provider classes for interact ing with a remote data
source. The nam es of t hese classes change slightly for each type of provider, but
each .NET data provider has the sam e four kinds of classes. The names for the
SQL Server .NET data provider classes for interacting wit h SQL Server instances
are SqlConnect ion, SqlCom m and, SqlDat aReader, and SqlDat aAdapter. You can
use the SqlDat aReader class for read-only applications from a SQL Server data
source. Two especially convenient ways to display results with a SqlDat aReader
class are in a m essage box or the Visual Studio .NET Output window. The
SqlDataAdapter class acts as a bridge between a remote SQL Server data source
and a Dat aSet class instance inside a Visual Basic .NET solution.
A data set in a Visual Studio solut ion is a fifth type of ADO.NET class. A data set
can contain multiple tables. A sixth ADO.NET class is the Dat aView class, which
acts like a view based on a table within a DataSet object. Windows Form s in
Visual Basic .NET applications can bind only to tables within a Dat aSet object and
Dat aView objects. I examine the Dat aSet object later in t his section. Chapter 10
includes a systematic summary of all six ADO.NET classes that reviews selected
properties and m ethods of each class. The overview of ADO.NET classes in
Chapter 10 is supported by numerous code samples that illustrate how to
manipulate instances of the classes program matically.
N ote
In order to use abbreviated names, such as those listed in
this section for the SQL Server .NET data provider class
instances, your application needs a reference to the SqlClient

namespace. You can create such a reference with an

I m ports
System.Data.SqlClient statement just before a Module
declaration.
SqlConnection Cla ss
An instance of the SqlConnect ion class can interface directly with a SQL Server
data source. Use a constructor statement to instantiate a SqlConnect ion object
from the SqlConnect ion class. The construct or st atem ent is a new type of sy-ntax
for .NET Framework solutions. This type of statement permits you to declare,
instantiate, and pass startup parameters to an object based on a class. With the
SqlConnect ion constructor statem ent, you can specify a connection string as an
argument for the constructor statem ent. Alternat ively, you can assign t he
connection string to the SqlConnection object after its instant iation with a
property assignm ent statement for the Connect ionSt ring property. The following
line shows the syntax to instantiate a new SqlConnect ion object, MySQLCnn1,
with a connection string designating integrated security to the mydb database on
the myserver instance of SQL Server. You don’t have to explicitly indicate a
provider because the constructor statem ent reveals the type of provider through
its reference to the SqlConnect ion class.
Dim MySQLCnn1 As New _
SqlConnection(“Integrated Security=SSPI;" & _
"Data Source=myserver;Initial Catalog=mydb")

After instantiat ing a SqlConnect ion object, you need to invoke its Open m ethod
before the object can link anot her object based on one of the other SQL Server
.NET data provider classes, such as SqlCom mand, SqlDat aAdapter, or
SqlDataReader, to a SQL Server instance. I nvoke the Close method to recover the
resources for a SqlConnect ion object when your solution no longer needs it. The
Close met hod rolls back any pending transactions and releases the connection to
the connection pool. The Dispose method is also available for removing
connections, but it invokes the Close method and performs other .NET

administrative functions. Microsoft recom mends the Close method for rem oving a
connection. Unclosed connections aren’t returned to the connection pool.
SqlCom m a nd an d SqlDat aReader Classes
One way t o put a connection to use is to employ it along with the SqlCom m and
and SqlDat aReader objects. A SqlDat aReader object can maintain an open
forward-only, read-only connection with a SQL Server database. While the
SqlDataReader using a SqlConnect ion object is open, you cannot use the
SqlConnect ion object for any other purpose except to close the connection.
Closing a SqlDataReader object releases its associated SqlConnect ion object for
other uses. The SqlDataReader class doesn’t have a constructor statement. You
declare the SqlDataReader obj ect with a Dim statement and assign a result set
from a SqlCom m and object to a SqlDat aReader wit h the ExecuteReader m ethod
of the SqlCom mand object. Finally, invoke the SqlDat aReader object Read
method to open a row from the result set in t he SqlDat aReader.
The SqlCom m and object can serve m ultiple functions, including processing a T-
SQL statement against a connection. When used in this fashion, the SqlCom m and
can take two argum ents. The first can be a T-SQL data access statem ent, such as
SELECT * FROM MyTable . The second SqlCom m and argument designates the
source connection for t he T-SQL statement. For exam ple, you can use the name
of a SqlConnection object, such as MySQLCnn1.
Figure 1-3 shows the route from a SQL Server data source to a SqlDataReader
object. Although the SqlConnect ion and SqlCom m and obj ects support two-way
interaction with a data source, the SqlDat aReader object allows read-only access
to the result set from the T-SQL statem ent serving as an argum ent for a
SqlCom mand constructor. Because a SqlDat aReader object cannot specify its own
data source, a SqlDataReader object must link to a SqlConnect ion object through
an intermediate SqlCom m and object.
Figu re 1 - 3. A schem atic illu strating the route b y w hich a SqlDataReader
object returns v a lues to an applica t ion.


The SqlCom m and object can do more than provide a result set to the
SqlDataReader object. The discussion of the SqlDat aReader object described the
use of the SqlCom mand object Execut eReader method. Three related methods
highlight som e contrasting SqlCom m and object functionality.
• Invoke the ExecuteNonQuery m ethod to perform two types of actions.
First, use this method to perform data definit ion tasks, such as creating
stored procedures and views. Second, the ExecuteNonQuery m ethod can
enable data manipulation tasks, such as inserts, updates, and deletes.
• Next, you can apply the ExecuteScalar method to a SqlCom mand object
when you want to return a single value from a SELECT statement. The
method returns the first colum n from the first row of a result set. If you
program this cell to be an aggregate value such as a count or sum , you
can readily extract that single value with the ExecuteScalar method.
• Finally, the ExecuteXMLReader m ethod opens a T-SQL source statem ent
with a FOR XML clause into an XMLReader object. Chapter 6 contains
extensive coverage of t he FOR XML clause. Objects for dealing with XML
will be covered in Chapter 12.
The SqlDa ta Adapt er Class a nd t he Dat aSet Class
You use objects based on the SqlDat aAdapt er class in combination with objects
based on the DataSet class. A Dat aSet object, which is an instance of the DataSet
class, represents an in-m emory cache of data retrieved from a database. The
Dat aSet obj ect offers a disconnected data source as opposed to the always-
connected data source for SqlDataReader objects. As a consequence, using the
SqlDataAdapter and Dat aSet objects instead of a SqlDat aReader object improves
application scalability. This scalability improvem ent results because the Dat aSet
doesn’t persist a connection to its underlying data source over the whole of its
lifetim e as does the SqlDat aReader object. While the SqlDataReader isn’t as
scalable as the SqlDat aAdapter/ Dat aSet com bination, the SqlDataReader can
provide faster performance from a rem ote data source because it delivers data in
the style of a forward-only, read-only cursor— the classic firehose delivery m odel.

N ote
The term firehose refers to the fact that data gushes out of a
forward-only, read-only cursor.
The SqlDat aAdapter and Dat aSet objects combine to enable both data access and
data manipulation capabilities. This is important because SqlDataReader objects
provide strictly data access capabilities (that is, you cannot perform update,
insert, or delete tasks with a SqlDataReader object). Use the SqlDat aAdapter Fill
method to populate a Dat aSet object with values from a SQL Server data source.
Because a single Dat aSet object can work with multiple SqlDataAdapter and OLE
DB Dat aAdapter objects, you can populate a single Dat aSet obj ect with
heterogeneous data sources from multiple database servers. For exam ple, you
can populate a single data set with tables, views, or stored procedures from two
different SQL Server instances or from Access and Oracle data sources in addition
to a SQL Server data source. Furt hermore, you can join all the data sources
within a Dat aSet object on fields with com mon data types.
Use the SqlDataAdapter Updat e method to transfer changes from a DataSet
object to its underlying data sources. When users perform insert, update, and
delete operations against the contents of a Dat aSet object, those modifications
don’t transfer to the data sources for the Dat aSet object until your application
invokes the Updat e method for a SqlDataAdapter object underlying the data
source. Despite its nam e, the Updat e method can process all three types of data
manipulation operations. However, you need a custom SqlCom mand object to
accommodate each type of data manipulation task. Therefore, a SqlDataAdapter
can relate to a remote data source through m ore than a single SqlCom m and
object. Between the time you populate the Dat aSet object and t he tim e your
application invokes the SqlDat aAdapter Updat e method, it’s possible for the
underlying data source on a SQL Server instance to change. Any changes can
cause exceptions because the original values in a data set can be different from
the current values in the SQL Server data source. The SqlDataAdapter has events
and properties to help m anage exceptions that can occur during an update

process. Figure 1-4 presents a schematic diagram summarizing how
SqlDataAdapter and Dat aSet objects exchange data with an underlying data
source. By contrasting this diagram with t he one in Figure 1-3, you can easily
spot an im portant difference between the SqlDataReader and a DataSet object
supplied by a SqlDat aAdapter object. The capability of perform ing data
manipulation with the DataSet object is a critical feature that m eans many
applications will rely on a DataSet object instead of a SqlDataReader object.
Figu r e 1 - 4. A schem atic illustrating the route by w h ich SqlD a t aAdapt er
and D a t a Set obj ects exchange values w ith a SQL Se rver da t a source .

The Dat aSet object offers an object m odel for managing the individual elem ents
within it. The DataSet object consists of a DataTable collection (along with other
elem ents). This collection can contain one or more tables. You can creat e these
tables with the SqlDat aAdapter Fill method when you initially populate a DataSet
object from a SQL Server data source. The Select Com mand property, which is a
T-SQL statem ent or a stored procedure, for a SqlDataAdapter object can serve as
the basis of a table in the Dat aTable collection for a DataSet object. You can use
multiple SqlDat aAdapter objects to add more than one table to a Dat aSet object.
Each table has a rich object m odel that permits the designation of prim ary keys
and foreign keys as well as constraints to manage data integrity within a table.
One very practical use for the Dat aTable collection and the object model for
individual tables is that you will use it to navigate among the values within a
Dat aSet obj ect.
N ote
In addition to referencing the column values of rows within
an individual DataTable in a DataSet object, you can
reference the schema of DataTable objects within a DataSet
object. This is particularly convenient when you want to
create a table that you want to populate with data from an
XML document.

The Dat aSet object supports four key m ethods for exchanging its data with XML
documents. Two of the methods are used for writing XML documents based on a
Dat aSet obj ect, and two are for reading XML documents into a Dat aSet object.
Within each pair, one method focuses just on transferring schem a information
and the other focuses on transferring data as well as schema information.


A St arter ADO.NET Sa m ple
This section presents a starter sample to illustrate som e of the concepts
described in the preceding section. Don’t worry about following the details of the
exam ple. I nstead, pay attention to how easy it is to get started with ADO.NET.
This section reinforces the presentation of basic ADO.NET concepts described in
the preceding section with simple drag-and-drop techniques and a little code
included to tie objects together or enable selected functionality. See Chapter 10
for a collection of code samples that illustrat e how to program ADO.NET objects
when you require customized solutions not readily available from the graphical
development environment. Most professional developers get called on to do the
hard work that goes beyond dragging and dropping objects. After all, if it were
easy, they wouldn’t need you. However, it is nice to start out by seeing how easy
it is to create a simple solution mostly by dragging and dropping.
N ote
For those who want the sample from this section as a point
of departure, it is available on the book’s CD as the
GraphicalDataBind solution.
Adding a SqlDataAdapt er, SqlConnect ion, a nd Data Set
You can drag a SqlDat aAdapter object to a form just like a text box or a com bo
box in Visual Basic 6. There is even a wizard to help you configure the
SqlDataAdapter object. Figure 1-5 shows the opening screen immediately after
dragging a SqlDat aAdapter object to t he startup blank form, Form 1, for a
Windows application. You can use this wizard to specify two ADO.NET objects.

Figu re 1 - 5. The D ata Ada pt e r Con figuration W izard enables you t o
graphica lly config ure a Sq lDataAdapter object and it s relat ed
SqlConnect ion obj e ct for use w it h a W ind ow s for m.

First, you can designate a SQL Server database to which to connect; this creates
a SqlConnection object. This wizard offers several routes for specifying a
database connection. For example, you can pick a previously created connection,
or you can create a new collection from the Data Link Properties dialog box. This
dialog box lets you specify the com mon connection string arguments, such as a
database server, a type of authent ication, and a database nam e. In this starter
sample, I used the default connection to the Northwind database.
Second, you can specify a data source within a database connection using a SQL
string or a stored procedure. For this starter application, I used SELECT
CategoryID, CategoryName FROM Categories as the SQL string source for the
SqlDataAdapter object. Although a graphical designer is available for building
query statem ents, you will be severely hampered as a SQL Server developer if
you don’t learn T-SQL, the dialect of SQL that SQL Server supports. I n addition,
you will find a grasp of T-SQL im portant for crafting the statem ents for the
SqlCom mand objects that enable you to build solutions that update a SQL Server
data source from a Windows application.
After you finish configuring the Data Adapter Configurat ion Wizard, the
component tray will open below your blank form. The tray will hold the two
objects that the wizard created— a SqlDataAdapter object and a SqlConnect ion
object. Because a SqlDat aAdapter object is merely a bridge between a remote
data source and a data set in a Windows application, you will need to create a
data set. Then your SqlDataAdapter object can fill the data set with data from the
rem ote data source specified by your replies to the Data Adapter Configuration
Wizard.
Immediately after a SqlDat aAdapter object is created, three links are displayed
near the bottom of the Properties window for the object. One of these links reads

Generate Dataset. Clicking t he link opens t he Generate Dataset dialog box, in
which you designate an existing data set or specify the name for a new one.
Figure 1-6 shows the specification of a new data set nam ed DsCat egories for the
SqlDataAdapter created with the Data Adapter Configuration Wizard. When you
click OK within the Generate Dataset dialog box portrayed in Figure 1-6, Visual
Basic .NET adds a new object named DsCat egories1 to the tray below the form.
In addition, Visual Basic .NET adds an XML schema named DsCategories.xsd to
the solution that describes the data set. You can view the schema for the data set
graphically or as XML code by double-clicking the file’s name in Solution Explorer.
The schema’s graphical view is interactive so that you can change the data type
specificat ion for columns and make other design changes to the Cat egories table.
The Properties window for the DsCat egor ies.xsd shows the nam e of the table
specificat ion as Cat egories. At this point, you have com pleted t he creation of the
DsCat egories data set, which contains a Dat aTable nam ed Cat egories.
Figure 1- 6. You need to add a data set before you can use a
SqlDataAdapter. You ca n add t h e data set as sim ply as giving it a nam e in
t h e Generate D at aset dialog box.

×