Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Program m ing Micr osoft ® SQL Server™ 2000 with Micr osoft Visual
Basic® .NET
Foreword
Acknow ledgm ent s
I ntroduct ion
Who’s the Book For?
What’s Special About This Book?
How’s the Book Organized?
Syst em Requirem ent s
Sam ple Files
Support
1. Get t ing St arted with Visual Basic .NET for SQL Server 2000
Visual St udio .NET, t he Visual Basic .NET I DE
An Overview of ADO.NET Capabilit ies
A St arter ADO.NET Sam ple
Using Query Analyzer
2. Tables and Data Types
Chapt er Resources
Data Types for Tables
Script ing Tables
3. Program m ing Dat a Access wit h T- SQL
I ntroduct ion t o Dat a Access w it h T- SQL
Aggregat ing and Grouping Rows
Processing Dat es
Joins and Subqueries
4. Program m ing Views and St ored Procedures
I ntroduct ion t o Views
Creat ing and Using Views
Views for Rem ot e and Het erogeneous Sources
I ntroduct ion t o Stored Procedur es
Creat ing and Using St ored Procedures
Processing St ored Procedure Out puts
I nsert ing, Updat ing, and Delet ing Rows
Program m ing Condit ional Result Set s
5. Program m ing User - Defined Funct ions and Triggers
I ntroduct ion t o User-Defined Functions
Creat ing and I nvok ing Scalar UDFs
Creat ing and I nvok ing Table- Valued UDFs
I ntroduct ion t o Tr iggers
Creat ing and Managing Triggers
6. SQL Serv er 2000 XML Funct ionalit y
Ov erview of XML Support
XML Form at s and Schem as
URL Access t o SQL Serv er
Tem plat e Access t o SQL Server
7. SQL Serv er 2000 Security
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Ov erview of SQL Server Secu rit y
I ntroduct ion t o Special Securit y I ssues
Sam ples for Logins and Users
Sam ples for Assigning Perm issions
8. Overview of t he .NET Fram ework
An I ntroduct ion t o the .NET Fram ework
An Overview of ASP.NET
XML Web Services
9. Creat ing Windows Applicat ions
Get t ing St arted w ith Windows Form s
Creat ing and Using Class References
I nher it ing Classes
Program m ing Event s
Except ion Handling for Run-Tim e Err ors
10. Program m ing Windows Solut ions with ADO.NET
An Overview of ADO.NET Obj ect s
Making Connect ions
Working with Com m and and Dat aReader Obj ect s
DataAdapt ers , Dat a Set s, Form s, and Form Controls
Modifying, I nserting, and Delet ing Rows
11. Program m ing ASP.NET Solutions
Review of ASP.NET Design I ssues
Creat ing and Running ASP.NET Solut ions
Session St at e Managem ent
Data on Web Pages
Validating the Data on a Web Page
12. Managing XML wit h Visual Basic .NET
SQL Server Web Releases
Ov erview of XML Technologies
Generat ing XML Docum ent s wit h t he .NET Fram ework
Dynam ically Set t ing an XML Result Set
Th e I nterplay Between XML and Data Sets
Creat ing HTML Pages wit h XSLT
13. Creat ing Solut ions wit h XML Web Ser vices
Ov erview of Web services
A Web Serv ice t o Ret urn a Com put ed Result
A Web Serv ice t o Ret urn Values from Tables
Th e SQL Server 2000 Web Services Toolk it
More on Populat ing Cont rols wit h Web Ser vices
About t he Aut hor
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Forew ord
During m y five years at Micr osoft, I ’ve been helping developers understand
technologies such as Micr osoft Visual St udio, Microsoft SQL Server, and Micr osoft
Office Developer. During t he past t wo years, I have w orked on the Microsoft
Office XP Visual Basic Language Reference, and now, t he MSDN Office Developer
Center. I n the m ont hly colum n on MSDN, Office Talk, I have writ t en art icles to
help Office developers understand the .NET plat form and how it affect s t heir
current and fut ure developm ent effort s.
As I writ e t his foreword to Rick Dobson’s book on program m ing Microsoft SQL
Ser ver solutions wit h Microsoft Visual Basic .NET, I think back to m y own
experiences developing software applicat ions with Visual Basic. My first
experience with Visual Basic was lear ning t he language using version 3.0. I
rem em ber picking up m y first Visual Basic beginner’s book and being excit ed as I
developed m y first few “ Hello, Wor ld” applications. I couldn’t believe how quick
and easy it was t o develop soft ware applicat ions that operat ed sim ilarly t o ot her
popular sharew are program s of that t im e.
How ev er, during that t im e I also discov er ed som e of t he shortcom ings of Visual
Basic as an ent erprise- level developm ent language. I t was then t hat I turned m y
at tent ion t o C+ + . I r em em ber being very frustrat ed at t r ying t o learn t he
language, trying to underst and concept s such as point ers, m em ory allocat ion,
and true obj ect -orient ed program m ing. I t ook classes on C+ + at t he local
universit y, but I got even m or e frust rat ed hav ing t o wait m onths unt il I was
taught how t o cr eat e t he sim plest Micr osoft Windows form , som et hing I did in
j ust a couple of m inut es using Visual Basic. I n m y frust rat ion, I gave up try ing t o
learn C+ + and have been using Visual Basic t o develop soft ware applicat ions ever
since.
As each new v ersion of Visual Basic was released, I readied m yself to learn new
soft w are developm ent t echnologies. First it w as Act iveX cont rol developm ent .
Then it was calling t he Windows API . Next it was DHTML Applicat ions. Then it w as
dat abase developm ent using Micr osoft SQL Ser ver. I t always seem ed as t hough I
had to learn a new language and a new developm ent paradigm for ev er y new
technology t hat cam e along. I kept t hink ing t hat there had to be an easier and
m ore unified appr oach.
Well, now we’ve reach ed the advent of the Micr osoft .NET plat form , and wit h it , a
revolut ion in the Visual Basic language, Microsoft Visual Basic .NET. I believe t hat
Visual Basic .NET will pr ovide software developers wit h new opportunit ies for
quick ly and easily designing int egrat ed software applicat ions t hat connect
businesses and individuals anyt im e, anywhere, and on virt ually any soft ware
device. Wit h advances in t he Visual Basic . NET language, Visual Basic .NET
developers w ill finally be on a par wit h t heir C+ + and C# counterparts,
participat ing in m any high-end developm ent proj ect s. Wit h Visual St udio .NET
feat ures such as cross- language debugging, along wit h Visual Basic .NET
conform ance to t he com m on t ype sy st em and t he com m on language runtim e,
organizat ions can drive down t heir developm ent cost s by t apping int o t he w ide
range of sk ills t hat Visual Basic .NET dev elopers now possess.
True obj ect -orient ed program m ing is now available in Visual Basic .NET, including
feat ures such as inheritance and m et hod ov er loading. I t ’s now sim pler t o call t he
Windows API by using the .NET Fram ework Class Libraries. Web applicat ion
developm ent is now as easy as developing Windows form s– based applicat ions.
Dat abase application developm ent is m ade easier by unit ing disparat e data obj ect
libraries such as DAO, RDO, OLE DB, and ADO under ADO. NET, ut ilizing the
power of XML t o consum e and transm it relat ional dat a over com put er net works.
And a new t echnology, XML Web services, allows Visual Basic .NET developers t o
host t heir soft w are applicat ions’ logic over t he Web. Addit ionally , a big issue for
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
soft w are developers t oday is that of soft war e applicat ion deploym ent and
versioning. I f you don’t agree, j ust ask any soft ware developer about “ DLL hell,”
and you’re bound t o get an earful. For m any .NET applicat ions, t he .NET plat form
feat ures “copy and past e” or XCOPY deploym ent . ( Users sim ply copy y our
applicat ion files from the source m edia t o any single directory and run t he
applicat ion.) And because .NET no longer relies on the regist ry, virtually all DLL
com pat ibilit y issues go away.
Wit h t his book, Rick aim s to give you t he skills you need t o pr ogram SQL Server
solut ions wit h Visual Basic .NET. I k now you will find Rick’s book helpful. Rick
brings his exper ience to bear from t hree previous books: Program m ing Micr osoft
Access Version 2002 (Micr osoft Press, 2001), Program m ing Micr osoft Access 2000
(Micr osoft Press, 1999) , and Professional SQL Server Development wit h Access
2000 ( Wrox Pr ess I nc., 2000). Rick also brings his exper ience of leading a
successful nat ionw ide sem inar t our. More im portant , I know you w ill enj oy Rick ’s
book because of his deep int erest in Visual Basic .NET and SQL Server, and in
helping you, t he pr ofessional developer, underst and and apply t hese t echnologies
in y our daily soft ware applicat ion developm ent proj ect s.
Paul Cornell MSDN Office Dev eloper Center
htt p: / / m sdn.m icr osoft.com / officeMicr osoft Corporat ion February 2002
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Acknow ledgm ent s
This sect ion offers m e a chance to say t hank you to all who helped m ak e this
book possible. I wish t o offer special recognit ion to five support resources.
First, the folks at Microsoft Press have been fant ast ic. Dave Clark, an acquisit ions
edit or, select ed m e t o writ e t he book j ust m onths aft er I com plet ed anot her book
for Microsoft Press. Dick Br own, m y pr oject edit or, staunchly st ood up for his
percept ion of how t o m ake t he book’s organization and cont ent clear to you
wit hout being pett y or boring t o m e. Dick also light ened m y load subst ant ially by
showing a real knack for edit ing m y t ext without dist orting the original int ent .
When Dick was especially busy, he handed off som e of his load to Jean Ross, w ho
also did an adm irable j ob. Ot hers at Microsoft Press who contribut ed t o m y well-
being in one way or anot her include Aaron Lavin and Anne Ham ilt on.
Second, I had excellent wor king relat ions wit h several professionals wit hin
Micr osoft . Paul Cor nell, a widely know n t echnical editor at Microsoft , was kind
enough t o share his insight s on how to present .NET concept s com pellingly. I
want t o t hank Paul especially for writ ing the Foreword t o t his book. Kart hik
Ravindran served as t he MSXML Bet a Product Lead Engineer at Microsoft Product
Support Services during t he t im e t hat I wrot e t his book. He provided valuable
technical cont ent about the SQL Server 2000 Web releases. Ot her Microsoft
represent atives pr oviding m oral and technical support for t his book include
Richard Waym ire and Jan Shanahan.
Third, I want t o express m y appreciation t o t he m any readers, sem inar
at tendees, and sit e visit ors who took t he t im e t o t ell m e what I did right or wrong
for t hem , and also to those w ho shared t heir t echnical support quest ions with m e.
I t is t hr ough t his kind of feedback t hat I am able to k now what’s im port ant t o
pract icing developers. I encourage you to visit m y m ain Web sit e
(ht t p: / / www.program m ingm saccess.com ) and sign t he guest book. The entry
for m includes space for you t o leave your evaluat ion of this book or your quest ion
about a topic covered in t he book. I prom ise t o do m y best t o r eply personally. I n
any event , I definitely read all m essages and use t hem so t hat I can serve you
bet t er with future edit ions of this, and ot her, books.
Fourt h, I want to t ell the world how grat eful I am to m y w ife, Virginia. Wit hout
Virginia’s w arm su pport , love, and care, this book would be less professional. She
relieves m e of nearly every r esponsibilit y around t he house w hen I undert ake a
book proj ect . I n addit ion, she offers strategic advice on t he issues t o address and
their st yle of cov erage. When I run out of t im e, she even pit ches in w it h the
proofreading.
Fift h, it is im portant for m e to give praise and glory t o m y Lord and Sav ior, Jesus
Christ , who I believe gave m e t he st rengt h and wisdom t o w rit e t his book. I n
addition, He gave m e healt h during t he long gestat ion period t hat result ed in the
birt h of t his book . I t is m y prayer that t he book prove t o be a blessing to y ou.
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
I nt roduct ion
Any one who buys a book—or considers buying it —w ant s t o k now w ho t he book is
for , what sets it apart fr om ot hers like it , and how t he book is organized. Th is
introduct ion covers those t hree quest ions, and it also discusses syst em
requirem ent s, sam ple files, and support.
• Fir st , w h o is t he book for? There are at least t wo answ ers to t his
question. One answ er is t hat t he book t argets professional developers
(and ot hers aspir ing t o be professional developers) . The second group t he
book addresses is those who want to build full- feat ured, secu re SQL
Server solutions wit h Visual Basic .NET.
• Se con d, w hat ’s special a bou t t h e book? I hope you com e t o believ e
that the m ost im portant answ er t o t his quest ion is t hat t he book
considered qualit y and depth of coverage m or e im portant t han rushing to
m arket . The book will arrive on bookshelves m ore than t hree mont hs aft er
the official release of t he .NET Fram ework. I t is m y w ish t hat you deriv e
value from t he ext ra t im e t aken to develop t he m any code sam ples and
the in-depth discussions of advanced topics, such as class inherit ance,
ASP.NET, and XML Web services.
• Third, h ow is t h e b ook orga n iz e d? The short answ er is t hat there are
two m ain sect ions. One section int roduces SQL Server concept s as it
dem onst rat es T- SQL ( Tr ansact SQL) pr ogram m ing techniques. After
conv eying SQL Server basic building block s in t he first part, t he second
part reveals how t o put t hose parts t ogether w it h Visual Basic .NET and
relat ed technologies into SQL Server solut ions for handling com m on
dat abase chores.
The t hree support item s include a brief descript ion of t he book’s com panion CD
and how t o use it , Micr osoft Press Support I nform at ion for t his book, and a
sum m ary of syst em and software requirem ent s for t he sam ple code pr esent ed in
the book.
W ho’s t he Book For ?
This book t arget s professional Visual Basic and Visual Basic for Applications
developers. From m y sem inar t ours and Web sit es
(ht t p: / / www.program m ingm saccess.com and ht t p: / / www.cabinc. net ) , I know
that these professionals are driven by a passion t o deliver solut ions to t heir
clients through applying t he m ost innovat ive t echnologies their client s will accept .
I n-house developers are t he go- t o persons for get t ing result s fast — particularly for
cust om in- house sy st em s and dat abases. I ndependent developers specialize in
serving niche sit uat ions t hat can include under-served business needs and work
ov erflows. I n bot h cases, t hese pr ofessionals need t raining m aterials that addr ess
pract ical business requirem ent s while showcasing innovat ive t echnologies without
wast ing their t im e. This book strives t o ser ve t his broad need in two specific
areas.
This book is for developers look ing for code sam ples and st ep-by-st ep inst ruct ions
for building SQL Server 2000 solut ions wit h Visual Basic .NET. The book focuses
on the int egrat ion of SQL Server 2000 w it h .NET t echnologies tapped v ia Visual
Basic .NET. I t is m y firm belief t hat y ou cannot creat e great SQL Ser ver solutions
in any program m ing language w it hout knowing SQL Server. Therefore, this book
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
goes beyond traditional coverage of SQL Server for Visual Basic developers. You’ll
learn T-SQL program m ing t echniques for dat a access, data m anipulat ion, and
dat a definition. A whole chapter equips you t o secur e your SQL Ser ver solutions.
I n addit ion, t here’s plenty of cont ent in t his book on Visual Basic .NET and relat ed
technologies, such as ADO.NET, ASP.NET, XML ( Extensible Markup Language),
and XML Web services. The present at ion of t hese t echnologies dem onstrat es
coding t echniques and explor es concepts that equip you t o build bet t er solut ions
wit h SQL Server 2000 dat abases. I n addit ion, t he book highlight s innovat ions
introduced through t he Web releases for SQL Server 2000 that int egrat e SQL
Ser ver 2000 tight ly wit h Visual Basic .NET.
This isn’t a book about XML, but t hree of the book ’s 13 chapt ers focus in whole or
in part on XML. Therefore, t hose seeking pract ical dem onst rat ions of how t o use
XML wit h SQL Server and Visu al Basic .NET w ill derive value fr om t his book. I f
you have looked at any of the com puter m agazines over t he past couple of years,
you know t hat XML is com ing to a solut ion near you. However, t he rapid pace of
XML innovat ion m ay have dissuaded som e from j um ping on t he bandwagon while
they w ait t o see what ’s going t o last and w hat ’s j ust a fad. I n t he book’s three
chapt ers on XML t echnology, you’ll learn about XML docum ents, fragm ent s, and
for m at t ing as w ell as r elat ed t echnologies, such as XPat h ( XML Pat h Language)
queries, XSLT ( Ext ensible St ylesheet Language Transform ation), and WSDL ( Web
Ser vices Descript ion Language) .
W ha t ’s Specia l About This Book?
Ther e are sev eral feat ures that m ake t his book st and apart from the flood of
books on .NET. One of the m ost im portant of t hese is that t his book didn’t rush t o
m arket but rat her shipped m ont hs aft er t he release of t he .NET Fram ework. This
allow ed m e enough t im e t o filt er, exam ine, and uncover what w ere t he m ost
useful and innovat ive feat ures for Visual Basic .NET developers building SQL
Ser ver solutions. For exam ple, the book includes a whole chapt er on creat ing
solut ions wit h XML Web services. That chapt er includes two m aj or sect ions on t he
SQL Server 2000 Web Services Toolk it , w hich didn’t ship unt il t he day of the .NET
Fram ework release.
The .NET Fram ework content is at a professional lev el, but it isn’t just for t echies.
This book doesn ’t assum e any prior know ledge of t he .NET Fram ework. I t does
assum e that you get paid for building solut ions program m atically and that at least
som e of those solut ions are for SQL Server dat abases. Therefore, t he book
explains basic .NET concept s and dem onst rat es how t o achieve pract ical result s
wit h those concept s t hrough a huge collect ion of .NET code sam ples.
This book is about building solut ions for SQL Server 2000. I include coverage of
the m any special feat ures t hat t ie Visual Basic .NET and SQL Server 2000 closely
to one anot her. Alt hough t here is coverage of general .NET database t echniques,
this book dives deeply int o T- SQL pr ogram m ing t echniques so that you can creat e
your own cu st om dat abase obj ect s, such as t ables, st or ed procedur es, view s,
triggers, and user-defined funct ions. I n addit ion, t here is separat e coverage of
the XML feat ures released wit h SQL Server 2000 as w ell as separat e coverage of
the XML feat ures in t he first t hr ee Web releases t hat shipped for SQL Server
2000. There are num erous code sam ples t hroughout t he book. These will equip
you to build solutions wit h Visual Basic .NET, T- SQL, and com binat ions of t he t wo.
Finally, t his book is special because of t he unique exper iences of it s author, Rick
Dobson. I have trained professional developers in Australia, England, Canada,
and t hr oughout t he Unit ed Stat es. This is m y fourt h book in four years, and you
can find m y articles in popular publicat ions and Web sit es, such as SQL Server
Magazine and MSDN Online. As a Webm aster, m y m ain sit e
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
(ht t p: / / www.program m ingm saccess.com ) serves hundreds of t housands of
sessions t o developers each year. I constant ly exam ine t heir viewing habits at t he
sit e to det erm ine what int erest s them . I n addit ion, m y site feat ures scores of
answers t o t echnical support quest ions subm itt ed by professional developers. My
goal in offering answers t o t hese quest ions is t o st ay in touch w it h pract icing
developers worldw ide so t hat my new book s address t he needs of pract icing,
professional dev elopers.
How ’s the Book Orga nized?
Ther e are t wo main part s t o t his book t ied t ogether by an int roductory part. Part
I I , t he first m ain part, dwells on SQL Server t echniques. Part I I I builds on the
SQL Server background as it lays a firm foundat ion in .NET techniques for Visual
Basic .NET developers. Part I , t he int roduct ory part, dem onst rates ways t o use
SQL Server and Visual Basic .NET t oget her.
Part I , I nt r oduct ion
Part I , which includes only Chapt er 1, has three m ain goals. Fir st , it acquaints y ou
wit h the basics of Visual Basic .NET w it hin Visual St udio .NET. You can t hink of
Visual Basic .NET as a m aj or upgrade t o t he Visual Basic 5 or 6 t hat you are
probably using current ly. This first sect ion int r oduces som e concept s t hat you w ill
find useful as you initially learn t he landscape of Visual Basic .NET. Th e second
goal of Chapt er 1 is to introduce ADO.NET. I f you think of Visual Basic .NET as a
m ajor upgrade to Visual Basic 6, ADO. NET is m ore like a m aj or overhaul of ADO.
I n t wo sect ions, you get an int roduction t o ADO.NET classes— part icularly as t hey
relat e t o SQL Server— and y ou get a chance t o see a couple of beginner sam ples
of how to create SQL Server solut ions wit h Visual Basic .NET and ADO.NET. Th e
third goal of t he int roductory part is to expose you to Query Analyzer . Th is is a
SQL Server client tool t hat sh ips wit h all com m ercial edit ions of SQL Server 2000.
You can t hink of it as an I DE for T- SQL code. Most of t he book’s first part relies
heavily on T- SQL, and t herefore having a conv enient environm ent for debugging
and running T- SQL code is helpful. The final sect ion of Chapt er 1 addresses this
goal.
Part I I , SQL Ser ve r
Part I I consist s of six r elat ively sh ort chapt ers that focus subst ant ially on
program m ing SQL Server 2000 wit h T- SQL. Chapt er 2 and Chapt er 3 int roduce T-
SQL and SQL Serv er dat a t ypes. I f you are going t o program SQL Ser ver and
create efficient , fast solut ions, you m ust learn SQL Server dat a t ypes, which is
one of t he main point s conveyed by Chapter 2. Many readers w ill grav it ate t o
Chapt er 3 because it int roduces core T- SQL pr ogram m ing t echniques for dat a
access. You’ll apply the t echniques covered in this chapt er often as you select
subsets of rows and colum ns in dat a sources, group and aggregat e row s from a
table, pr ocess dat es, and j oin dat a from t wo or m ore t ables. Chapt er 3 also
considers special dat a access t opics, such as outer j oins, self joins and
subquer ies.
The next pair of chapt ers in Part I I , Chapt er 4 and Chapter 5, t ake a look at
program m ing database obj ect s t hat you will use for dat a access and dat a
m anipulat ion, such as view s, st ored procedures, user- defined funct ions, and
triggers. These dat abase obj ect s are im port ant for m any reasons, but one of t he
m ost im portant is t hat they bundle T- SQL st at em ent s for t heir easy reuse. I t is
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
widely know n that t he best code is the code t hat you don’t have t o writ e.
How ev er, if you do have t o write code, you should definit ely writ e it j ust onc, and
then reuse it whenever you need its funct ionalit y. St ored pr ocedures are
particu larly desirable dat abase obj ect s because t hey save com piled T- SQL
st at em ent s t hat can deliver significant speed advantages over resubm it t ing the
sam e T- SQL st atem ent for com pilat ion each t im e y ou want t o perform a dat a
access or dat a manipulat ion t ask. Chapt er 4 and Chapt er 5 are also im port ant
because t hey convey T- SQL sy nt ax for using param et ers and condit ional logic
that support dynam ic r un-t im e behavior and user int eract iv it y.
One of t he m ost im port ant feat ures of SQL Server 2000 is it s XML functionalit y.
Because XML as a t opic is changing so rapidly, Micr osoft adopt ed a strat egy of
upgrading t he SQL Server 2000 XML funct ionalit y through Web releases. Alt hough
those with SQL Server 2000 can download t he Web releases without charge from
the Microsoft Web sit e, the Web releases are fully supported. Chapt er 6
introduces core XML funct ionalit y int roduced w it h SQL Ser ver 2000 as well as
funct ionality from t he fir st t wo Web releases. I n part icular, y ou can learn in t his
chapt er about I I S virt ual direct ories as well as form at s for XML docum ent s and
schem as. You also learn about tem plat es in virt ual direct ories that facilitat e data
access and dat a m anipulat ion t asks over t he Web.
Chapt er 7 closes out the SQL Ser ver part of t he book w it h an in-dept h look at
program m ing SQL Server security. I n t hese t im es, securit y has grown int o a
m onum ent al t opic, and this chapt er can keep you out of t rouble by blocking
hackers from getting int o or corrupt ing y our dat abase. You learn such t opics as
how t o cr eat e and m anage different t ypes of login and user account s and how t o
cont rol t he perm issions available to individual account s as well as groups of
account s. By learning how t o script account s and perm issions with T- SQL, you
sim plify revising and updat ing security as condit ions ch ange ( for exam ple, when
users leave t he com pany or when new, sensit ive dat a gets added t o a t able) .
Part I I I , .N ET
Chapt er 8 st arts t he .NET part of t he book w it h a review of select ed .NET t opics
that ar e covered in the initial look Chapt er 1 offered at t he .NET Fram ewor k. This
chapt er prov ides an overview of t he archit ect ur e for .NET solut ions, and it drills
down on t wo topics: ASP.NET and XML Web services. The general purpose of this
chapt er is t he sam e as Chapt er 1 , w hich is to introduce concept s. The em phasis
in Chapt er 8 isn’t how you do som et hing, but rather what are t he m aj or
technologies enabling you t o do som ething. Chapt er 1 and Chapter 8 are bot h
relat ively sh ort chapt ers, but you m ay find them invaluable if y ou are t he k ind of
person who benefits from high-level overviews of a collect ion of t opics.
Chapt er 9 st arts w ith a close exam inat ion of how to use Windows Form s wit h
Visual Basic .NET. I t t hen sh ift s its focus to a review of t raditional class
processing concept s via Visual Basic .NET as an int r oduct ion t o class inherit ance,
a new obj ect -orient ed feat ure t hat mak es it s first appearance in Visual Basic wit h
Visual Basic .NET. Next t he t r eat m ent of classes progresses to t he handling of
built - in event s as well as the raising of cust om event s. Finally the chapt er closes
wit h an exam inat ion of the new exception handling techniques for processing run-
tim e errors.
Chapt er 10 is a how - t o guide for solutions t o t y pical problem s wit h ADO.NET.
Before launching into it s progression of sam ples show ing how to perform all k inds
of task s, t he chapt er st arts with an ov er view of the ADO.NET object m odel that
covers t he main obj ect s along wit h select ed propert ies and m et hods for each
obj ect . The how- t o guide focuses on dat a access t asks, such as select ing rows
and colum ns from SQL Ser ver database obj ect s, as well as data m anipulat ion
tasks, such as insert ing, updat ing, and delet ing rows in a table. Working t hr ough
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
the sam ples in t he how - to guide offers a hands-on feel for using t he
System .Dat a.SqlClient nam espace elem ents to perform t ypical t asks.
Chapt er 11 sw itches t he focus t o the Web by addressing t he cr eat ion and use of
ASP.NET solut ions. This chapt er st arts by int r oducing basic elem ent s that you
need t o know in order to use ASP.NET t o cr eat e great Web solut ions wit h Visual
Basic .NET. These include learning what happens as a page does a round-trip
from a browser t o a Web server and back to the browser— part icularly for data
associated with the page. Ot her prelim inary t opics t hat equip you for building
professional Web solutions include running t he sam e page in m ult iple browser
types and sniffing t he browser for cases in w hich you w ant t o send a page
opt im ized for a specific kind of browser t ype. Managem ent of session st at e is a
m aj or topic in t he ch apt er, and you lear n how t o use enhancem ent s t o Session
variables for Web farm s as well as the new v iew st at e var iables, a non-server-
based t echnique for m anaging stat e in ASP.NET solut ions. The last t wo sections in
the chapt er deal with ADO.NET t opics in ASP.NET solutions and t he new
aut om at ic data validat ion feat ures built right into ASP.NET.
The last t wo chapt ers in the book explore how XML interplays wit h Visual St udio
.NET and SQL Server 2000. For exam ple, Chapt er 12 exam ines special t ools in
Visual St udio .NET to facilitat e t he design and edit ing of XML docum ent s and
schem as. I n addit ion, you learn how t o designat e XPat h queries t hat accept run-
tim e input for ret urning SQL Server result sets inside Visu al Basic .NET program s.
The chapt er dem onst rat es techniques for processing the XML docum ent
associated with all ADO.NET dat a set object s. I n t he chapt er’s last section, I
present a couple of code sam ples t hat illust rate how t o pr ogram st atic HTML
pages based on XML docum ent s wit h XSLT.
Chapt er 1 3 drills down on XML Web services by dem onst rat ing several different
approaches for creat ing Web services as w ell as consum ing XML out put from Web
services. Web services behave somew hat like COM object s in t hat you can set up
server applications for client applicat ions. The ser ver applicat ions expose m ethods
to which the client applicat ions can pass param eters. XML comes int o play wit h
Web services in a couple of areas. First , Web ser vices represent t heir inputs and
out put s via WSDL, an XML-based language t hat form ally describes an XML Web
service. Second, Web ser vices ret urn dat a t o t heir client s as XML docu m ent s or
docum ent fragm ents.
Syst em Require m ents
The requirem ent s for t his book var y by chapter. I developed and t est ed all
sam ples throughout t his book on a com puter equipped w it h Windows 2 000
Ser ver, SQL Server Ent erprise Edit ion, and t he Ent erprise Dev eloper Edit ion of
Visual St udio .NET, w hich includes Visual Basic .NET. To use t his book, you’ll need
to have Visual Basic .NET or Visual St udio .NET installed on your com put er. (See
Chapt er 1 for m or e inform at ion on versions of Visual Basic .NET and Visual St udio
.NET.) I n addit ion, you’ll need SQL Server 2000, and for som e of the chapt ers,
you’ll need SQL Server 2000 updated wit h Web releases 1, 2, and 3. Chapt er 6
giv es the URLs for downloading Web releases 1 and 2. Chapt er 12 gives t wo
different URLs for downloading Web Release 3— one w it h t he SQL Server 2000
Web Ser vices Toolkit and t he ot her wit hout it .
For select ed chapt ers, you can run the sam ples wit h less software or different
operat ing sy st em s than the one t hat I used. For exam ple, chapt ers 2 through 5
will run on any operat ing sy stem that supports a com m ercial version of SQL
Ser ver 2000, such as Windows 98 or a m ore recent Windows operat ing syst em .
Chapt er 7 requires an operat ing syst em that support s Windows NT securit y, such
as Windows 2000 or Windows XP Professional. Chapt er 6, Chapt er 11, and
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Chapt er 1 3 r equir e Micr osoft I nternet I nform at ion Services (I I S) . I n addit ion,
Chapt er 6 requires t he installat ion of Web releases 1 and 2. For Chapt er 11, your
syst em needs t o m eet t he m inim um requirem ent s for ASP.NET. (See a not e in t he
“How Does ASP.NET Relate t o ASP?” section of Chapt er 8.) Several of t he
sam ples in Ch ap t e r 1 3 require Web Release 3 and its associated SQL Server
2000 Web Services Toolkit .
Sa m ple Files
Sam ple files for t his book can be found at the Microsoft Press Web sit e, at
htt p: / / www.m icrosoft .com / m spress/ books/ 5792.asp. Clicking the Com panion
Cont ent link t akes you t o a page from w hich you can dow nload the sam ples.
Supplem ent al cont ent files for t his book can also be found on t he book’s
com panion CD. To access those files, insert t he com panion CD into y our
com put er’s CD- ROM drive and m ake a select ion fr om t he menu t hat appears. I f
the Aut oRun feat ure isn’t enabled on your sy st em ( if a m enu doesn’t appear when
you insert the disc in y our com put er’s CD- ROM drive), r un St art CD.exe in the root
folder of t he com panion CD. I nst alling t he sam ple files on your hard disk requir es
approx im at ely 15.3 MB of disk space. I f y ou have t rouble running any of t hese
files, refer t o t he t ext in the book t hat describes these program s.
Aside from t he sam ple files t hat t his book discusses, the book’s supplem ent al
cont ent includes a st and-alone eBook inst allat ion t hat w ill allow you t o access an
elect ronic version of t he print book direct ly from your deskt op.
Su pport
Ev er y effort has been m ade t o ensu re t he accuracy of t his book and t he content s
of the com panion CD. Micr osoft Press prov ides correct ions for books t hrough the
World Wide Web at the following address:
htt p: / / www.m icrosoft .com / m spress/ support
To connect direct ly t o t he Micr osoft Press Know ledge Base and ent er a query
regarding a quest ion or an issue t hat you m ay have, go t o:
htt p: / / www.m icrosoft .com / m spress/ support / search.asp
I f you have com m ent s, quest ions, or ideas regarding this book or t he com panion
cont ent , or quest ions that are not answered by querying the Knowledge Base,
please send t hem to Microsoft Pr ess via e-m ail to:
m spinput@m icr osoft .com
Or via postal m ail t o:
Micr osoft Press At tn: Program m ing Microsoft SQL Ser ver 2000 wit h Microsoft
Visual Basic .NET Editor One Micr osoft Way Redm ond, WA 98052-6399
Please not e t hat product support is not offered through t he above m ail address.
For product support inform at ion, please visit the Microsoft Support Web sit e at :
htt p: / / su pport.m icrosoft.com
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Cha pt er 1 . Get t ing St ar t e d w it h Visual
Basic .N ET for SQL Serve r 2 0 0 0
This book aim s t o give professional developers t he background t hat they need t o
program SQL Server applications w it h Micr osoft Visual Basic .NET. This overall
goal im plies t hree guidelines:
• First, the book target s pract icing developers. I n m y experience, t hese ar e
busy professionals who need the det ails fast . These individuals already
know how t o build applicat ions. They buy a book t o learn how to build
those applicat ions wit h a specific set of tools.
• Second, the book is about building applicat ions for SQL Server 2000. This
focu s j ust ifies in-dept h coverage of SQL Server program m ing t opics— in
particu lar, T- SQL, Micr osoft ’s extension of t he St ruct ured Qu ery Language
(SQL) .
• Third, the book illust rat es how t o pr ogram in Visual Basic .NET, but wit h
particu lar em phasis on database issues for SQL Ser ver 2000. Special
at tent ion goes t o relat ed .NET t echnologies, such as the .NET Fram ew ork,
ADO.NET, ASP.NET, and XML Web ser vices.
My goal in t his chapt er is to equip you concept ually for t he rest of t he book .
Ther efore, t his chapter includes m at erial that acquaint s you w it h applicat ion
developm ent t echniques and t opics for SQL Server 2000 and Visual Basic .NET.
The discussion of t he sam ples in t his chapt er generally aim s t o convey broad
approaches inst ead of how t o r un t he sam ple. All t he r em aining chapt ers except
for Chapter 8, anot her conceptual chapt er, have sam ples with inst ruct ions aim ed
at professional developers.
I believe t hat t he overwhelm ing m aj ority of pr ofessional Visual Basic developers
hav e no hands-on fam iliarity wit h Visual Basic .NET and its relat ed t echnologies.
I f you already knew Visual Basic .NET, it wouldn’t m ake any sense t o buy a book
descr ibing how t o use it . This ch apt er t herefore focuses on how t o get st art ed
wit h Visual Basic .NET and one of its core relat ed technologies for t hose building
SQL Server applicat ions— ADO. NET. I also believe t hat m ost Visual Basic
developers don’t have an int im at e know ledge of SQL Server— especially for
creating user-defined obj ects, such as t ables, view s, and st ored procedures. This
capabilit y can em pow er you t o build m ore powerful and m or e secure applicat ions.
As y ou lear n about dat abase obj ect s and how t o creat e t hem in Chapt er 2
through Chapter 7, reflect back on t he Visu al Basic .NET coverage in t his chapter
and how t o marry database creat ion t echniques and Visual Basic .NET
developm ent t echniques. One of t he best t ools to build database obj ect s is SQL
Ser ver 2000 Query Analyzer. This chapt er’s closing sect ion conveys the basics of
Query Analyzer that you need t o follow t he sam ples in Chapt er 2 t hrough Chapter
7.
Visua l Studio .N ET, the Visual Basic .N ET I D E
Visual St udio .NET is t he new m ult ilanguage int egrat ed developm ent environm ent
(I DE) for Visual Basic, C# , C+ + , and JScr ipt developers. I f you are developing
solut ions for Visual Basic .NET, I definitely recom m end t hat you use Visual St udio
.NET as your developm ent environm ent . This section dem onstrates how t o get
st arted using Visual St udio .NET for developing solut ions wit h Visual Basic .NET.
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Visual Basic .NET is available as part of Visual St udio .NET in four edit ions:
• Professional
• Enterprise Developer
• Enterprise Archit ect
• Academ ic
All four edit ions of Visual St udio .NET include Visual Basic .NET, Micr osoft Visual
C# .NET, Microsoft Visual C+ + .NET, and support for ot her languages. I n
addition, Microsoft offers Visual Basic .NET St andard, w hich doesn’t include Visual
C# .NET or Visual C+ + .NET.
Because t his book targets professional Visu al Basic developers creat ing SQL
Ser ver applications, it uses t he Ent erprise Developer Edition of Visual St udio
.NET. You m ay not ice som e differences if you’re using anot her edit ion.
Visual St udio .NET can be inst alled on com put ers running one of five operat ing
syst em s: Windows 2000, Windows NT, Windows XP, Windows ME, and Windows
98. Not all the .NET Fram ework features are available for each operat ing syst em .
For exam ple, Windows 98, Windows Me, and Windows NT don’t support
developing ASP.NET Web applicat ions or XML Web services applications. The
sam ples for t his book ar e test ed on a com puter running Windows 2000 Ser ver,
which does support all .NET Fram ework feat ures.
St art ing Visual St udio .N ET
To open Visual St udio .NET, click t he St art butt on on t he Windows t ask bar,
choose Program s, and then choose Micr osoft Visual St udio .NET. Visual Studio
displays it s int egrat ed developm ent environm ent , including t he Start Page ( unless
you previously configured Visual St udio t o open different ly). Fr om the St art Page,
you can configure Visual St udio to work according to y our developm ent
preferences, and you can st art new solut ions as well as open exist ing proj ect s.
Con figuring Visua l St udio .N ET for Visual Ba sic .N ET
Use the links on the left side of t he St art Page t o begin configur ing Visual Studio
.NET for developing solut ions in Visual Basic .NET. Click the My Profile link t o
open a pane in w hich you can specify an overall profile as well as individually
indicat e your preferences for Keyboard Schem e, Window Layout, and Help Filter.
You also can designat e t he init ial page t hat Visual Basic .NET displays. When y ou
are beginning, it m ay be part icular ly convenient t o choose Show St art Page. As a
Visual Basic developer who has worked w it h Visual Basic 6, you m ight feel m ost
fam iliar wit h a lay out t hat reflect s your pr ior developm ent env ironm ent . Figure 1-
1 shows t hese My Profile select ions.
Figure 1 - 1 . M y Profile se lections for st a r t ing Visual St u dio .NET for a
Visu a l Basic developer.
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Using t he Start Page
Aft er setting your profile, you can ret urn t o the init ial Start Page pane by
choosing t he Get St art ed link from t he m enu on t he left border. I f you had
created previous solutions, t he last four m odified proj ect s would appear on the
Proj ect s tab of t he Start Page. The tab sh ows pr oject nam es along w it h date last
m odified. I f a pr oj ect y ou want t o v iew doesn’t appear on t he list , you can click
the Open Project link t o display t he Open Proj ect dialog box and t hen navigat e t o
a direct ory cont aining t he previously cr eat ed solut ion. Select the proj ect ’s folder
that you want t o open in the I DE, and double- click t he solution file (.sln) for t he
proj ect . The next sect ion illust rat es t his process in the context of a sam ple
proj ect .
To creat e a new solution, click the New Proj ect link t o open t he New Proj ect
dialog box. I f you saved preferences such as those sh own in Figure 1-1, t he
dialog will aut om at ically select Visual Basic Proj ect s in the Proj ect Types pane of
the New Proj ect dialog box. On t he right, you can select a t em plat e for launching
a proj ect . Table 1- 1 sh ow s t he proj ect t em plat e nam es along wit h a brief
descr ipt ion available from t he Ent erpr ise Dev eloper Edit ion of Visual Studio .NET.
Choosing a t em plat e (by clicking OK aft er select ing a t em plat e) opens a proj ect
ready for cr eat ing the t ype of solut ion t hat y ou w ant t o develop. When Visual
St udio .NET saves the tem plat e t o st art a new project , it specifies eit her a file
folder or a Web sit e for the tem plat e’s files; you can override t he default nam es
for t he file folder and Web site.
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
N ote
Not all the proj ect tem plat e types in Table 1- 1 are available
with the non- Enterprise (or St andard) editions of Visual
Studio .NET. I n addition to the em pty proj ect s, the St andard
editions m ake available t he Windows Application, ASP.NET
Web Applicat ion, ASP.NET Web Service, and Console
Application tem plates.
7DEOH9LVXDO%DVLF1(73URMHFW7HPSODWH7\SHV
7HPSODWH1DPH &UHDWHV$
Windows
Applicat ion
Windows applicat ion w it h a form
Class Library Windows applicat ion suitable for a library of classes without a
form
Windows Control
Librar y
Proj ect for developing cust om reusable form controls for
Windows applicat ions
ASP.NET Web
Applicat ion
Web applicat ion on a Web server
ASP.NET Web
Service
XML Web service on a Web server
Web Cont rol Library Proj ect for dev eloping custom reusable cont rols for Web
applications
Console Applicat ion Com mand line application that operates in an MS- DOS–style
window (the Console)
Windows Service Windows service, form erly NT service, application that runs
in t he background w it hout it s ow n cust om user int erface
Em pt y Proj ect Local pr oj ect with no cust om st yle
Em pt y Web Proj ect Web proj ect wit h no custom st yle
New Proj ect I n
Ex ist ing Folder
Blank proj ect in an exist ing folder
Ther e are t wo main cat egories of tem plat es: Web proj ect s and local proj ect s. Web
proj ect s perm it a browser to serve as the client for a proj ect . Web pr oj ect s are
opt im ized for form processing on t he Web server. Local project s offer cust om
for m user int erfaces wit h the capabilit y of processing on a local w orkst at ion. Local
proj ect s can prov ide richer environm ents m ore conduciv e t o client -side
program m ing, but local proj ect s don’t offer the wide accessibilit y of solut ions
running from a Web server.
Crea t ing and Running a Console Applicat ion
When you select a Console Application t em plat e and click OK to launch a new
proj ect , Visual St udio .NET responds by opening a proj ect w it h a blank module. I n
addition t o t he Module window, Visual St udio displays Solut ion Explorer and the
Properties window. You can ent er code direct ly int o t he Module window, w hich
appears as a tab t hat y ou can select alt ernat ely wit h t he St art Page. Figure 1-2
shows a code sam ple in t he Main su brout ine t hat prom pts for a first and second
nam e before com bining them and display ing them in t he Console (t he com put er’s
m onit or). The code is also available as My Nam eI sFrom Console in the Chapt er 1
folder on t he com panion CD for t his book. Alt hough Visual Basic developers didn’t
previously have Console applicat ions rout inely available, t his sam ple sh ould be
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
very easy to follow. The final two lines present an inst ruct ion and cause the
window t o rem ain open unt il the user responds to t he inst ruct ion. This allow s the
user t o view t he full nam e in the Console w indow.
Figure 1 - 2 . A Con sole applicat ion for displayin g a full n a m e based on use r
input for fir st and second n a m e s.
To the right of t he Module window are two other windows. The t op one of t hese is
Solut ion Explorer. I t shows the file st r uct ure for t he solut ion. Solut ion Explor er
indicat es in it s first line t hat the solut ion consist s of j ust one proj ect . Below t hat
line appears t he nam e of the proj ect , My Nam eI sFrom Console. Wit hin the proj ect
are t hree entries: one each for t he References, Assem blyI nfo.v b, and Module1.vb
elem ent s wit hin t he solut ion’s proj ect . By default , t he Propert ies window is below
Solut ion Explorer. I n the Full Pat h propert y t ext box is an excerpt show ing t he
pat h t o Module1.vb on m y com put er . When you click the proj ect nam e in Solut ion
Explorer, t he Proj ect Folder t ext box in t he Propert ies window displays t he path of
the dir ect ory holding the solut ion’s files. I t is t his direct ory that you copy to
deploy your solution on anot her com puter w it h t he .NET Fram ework inst alled. The
solut ion won’t run wit hout the com m on language runt im e on t he com puter t o
which you copy t he direct ory cont aining t he .NET Fram ew ork solut ion. See
Chapt er 8 for m or e det ailed cov erage of the .NET Fram ework, including t he
runt im e and dist ribut ing .NET Fram ework solut ions as assem blies of files in
folders.
You can t est run t he applicat ion by ch oosing St art from t he Debug m enu, or by
pressing F5. This opens t he Console w indow wit h a prom pt t o ent er a first nam e.
Aft er you close y our applicat ion and save any changes to it , y our solut ion appears
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
on the St art Page for recent solutions. I f you st art Visual St udio .NET and the
solut ion you w ant t o open doesn’t appear on the Proj ect s tab of t he St art Page,
you can also open t he solut ion by click ing Open Proj ect . I n t he Open Proj ect
dialog box, ch oose t he file wit h t he .sln extension and t he solut ion’s nam e
(MyNam eI sFrom Console) . A solut ion can contain j ust one .sln file, but it can
cont ain m ult iple proj ect s.
You also can run t he solut ion and open t he Console window direct ly from
Windows Explorer wit hout using Visual St udio .NET. Open t he bin subdirect ory
wit hin t he direct ory cont aining the assem bly folder for t he solut ion. Then double-
click the MyNam eI sFrom Console.exe file. This opens t he Console w indow wit h the
prom pt for a first nam e.
An Overview of AD O.N ET Capabilit ies
ADO.NET encapsulat es t he dat a access and dat a m anipulat ion for t he .NET
Fram ework. This sect ion gives you an overview of t he t opic that equips you for a
st arter sam ple in t he next sect ion. Microsoft ch ose t he nam e ADO.NET for t he
.NET Fram ew ork dat a access com ponent to indicat e its association w it h the earlier
ADO t echnology for dat a access. While t her e are som e sim ilarit ies in sy nt ax
bet ween ADO.NET and ADO (part icu larly for connect ion st rings) , m any will find
the differ ences are m ore obvious t han t he sim ilarit ies. These differences
subst ant ially upgrade ADO.NET over ADO in two key areas— scalabilit y and XML
(Ext ensible Markup Language) interoperabilit y. As a result , you will be able t o
create database applicat ions w it h ADO.NET t hat serve m or e users and shar e m ore
dat a than you did w it h ADO. See Chapt er 10 for a m ore intensive exam inat ion of
ADO.NET. Chapt er 12 explicit ly explores int eroperabilit y bet ween ADO. NET and
XML.
.NET D at a Pr ovide r Types
Your .NET Fram ework solut ions requir e .NET dat a providers t o connect t o data
sources. These pr oviders are different from t hose used wit h ADO, but t here are
dist inct similarit ies in som e of the ways y ou use t hem . Wit h .NET dat a providers,
your solut ions can connect , r ead, and execute com m ands against data sources.
The .NET providers also offer select ed ot her funct ions, such as t he m anagem ent
of input and out put param eters, securit y, t ransact ions, and database ser ver
errors.
Visual St udio .NET ships wit h two .NET data providers— t he SQL Server .NET dat a
provider and the OLE DB .NET dat a provider. I n addit ion, you can dow nload an
ODBC .NET data provider from t he Micr osoft MSDN download sit e
(ht t p: / / m sdn.m icrosoft .com / downloads/ default .asp).
N ote
As I write this chapter, t he ODBC .NET data provider just becam e
available with the rollout of the shipping version of Visual St udio
.NET. You can download it fr om
ht tp: / / m sdn.m icr osoft.com / downloads/ default.asp?url= / downloads/ s
am ple.asp?url= / m sdn-files/ 027/ 001/ 668/ m sdncom posit edoc.xm l.
The URLs for resources som etim es change. You can always search
for the ODBC .NET data provider at t he MSDN download site to
obt ain its current download locat ion.
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
The three prov iders t aken together offer fast , highly focused access t o select ed
dat a sources as well as general access t o a wide range of possible data sources.
The SQL Server .NET data provider is opt im ized for SQL Ser ver 7.0 and SQL
Server 2000. This dat a provider connect s direct ly t o a SQL Server instance.
The OLE DB .NET dat a prov ider connect s t o OLE DB dat a sources through t wo
interm ediat e layers— t he OLE DB Service Com ponent and the classic OLE DB
provider int roduced along wit h ADO. The OLE DB Service Com ponent m anages
connect ion pooling and t ransact ion services. The classic OLE DB provider, in turn,
dir ect ly connect s t o a dat abase server. Micr osoft explicitly t est ed t he OLE DB .NET
dat a provider wit h SQL Server, Oracle, and Jet 4.0 databases. Use t he OLE DB
.NET dat a provider t o connect t o t he SQL Serv er 6.5 v ersion and earlier ones.
This provider is also good for connect ing t o y our Micr osoft Access solutions based
on the Jet 4.0 engine.
The OLE DB .NET dat a prov ider definit ely doesn’t work wit h t he OLE DB provider
for ODBC dat a sources (MSDASQL) . Because t he .NET OLE DB dat a pr ovider
doesn’t connect to ODBC data sources, you require t he ODBC .NET dat a provider
for connect ing t o ODBC dat a sources fr om y our .NET Fram ew ork solut ions.
Ther e are four m ain .NET dat a pr ovider classes for int eract ing w it h a rem ot e dat a
source. Th e nam es of t hese classes change slightly for each t ype of prov ider, but
each .NET dat a provider has the sam e four kinds of classes. The nam es for the
SQL Server .NET dat a provider classes for int eract ing wit h SQL Server instances
are SqlConnect ion, SqlCom m and, SqlDat aReader, and SqlDataAdapt er. You can
use t he SqlDataReader class for read-only applicat ions fr om a SQL Server dat a
source. Tw o especially convenient ways t o display result s wit h a SqlDat aReader
class are in a m essage box or the Visual St udio .NET Out put w indow. The
SqlDat aAdapt er class act s as a bridge between a r em ot e SQL Server dat a source
and a DataSet class inst ance inside a Visual Basic .NET solution.
A dat a set in a Visual St udio solut ion is a fift h t ype of ADO.NET class. A data set
can contain m ult iple t ables. A sixt h ADO.NET class is t he DataView class, w hich
act s lik e a view based on a t able w it hin a Dat aSet obj ect . Windows Form s in
Visual Basic .NET applicat ions can bind only t o t ables wit hin a Dat aSet obj ect and
Dat aView obj ect s. I exam ine the DataSet obj ect lat er in t his sect ion. Chapt er 10
includes a sy st em at ic sum m ary of all six ADO.NET classes that reviews select ed
propert ies and m et hods of each class. The overview of ADO.NET classes in
Chapt er 10 is supported by num erous code sam ples t hat illust rat e how t o
m anipulat e inst ances of t he classes program m at ically.
N ote
I n order to use abbreviated nam es, such as those list ed in
this sect ion for the SQL Server .NET data provider class
inst ances, your application needs a reference to the SqlClient
nam espace. You can cr eat e such a reference with an I m port s
Syst em .Data.SqlClient statem ent just before a Module
declaration.
SqlConne ct ion Cla ss
An inst ance of the SqlConnection class can int erface direct ly wit h a SQL Serv er
dat a source. Use a const ructor st at em ent t o inst antiat e a SqlConnect ion object
from t he SqlConnect ion class. The const ruct or st at em ent is a new t ype of sy- nt ax
for .NET Fram ework solut ions. This type of stat em ent perm its you to declare,
inst ant iat e, and pass startup param et ers to an obj ect based on a class. Wit h the
SqlConnect ion construct or st at em ent , you can specify a connect ion string as an
argum ent for the const ruct or st at em ent . Alt ernat iv ely, you can assign t he
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
connect ion st ring to t he SqlConnect ion object aft er it s inst ant iat ion w it h a
propert y assignm ent st atem ent for t he Connect ionString property. The following
line shows the synt ax to inst antiat e a new SqlConnect ion obj ect , My SQLCnn1,
wit h a connect ion st r ing designat ing integrat ed secur it y to t he m ydb dat abase on
the m yserver inst ance of SQL Server. You don’t have t o explicit ly indicat e a
provider because t he const ruct or st at em ent reveals t he t ype of provider t hrough
it s refer ence t o the SqlConnect ion class.
Dim MySQLCnn1 As New _
SqlConnection(“Integrated Security=SSPI;" & _
"Data Source=myserver;Initial Catalog=mydb")
Aft er inst ant iat ing a SqlConnect ion obj ect , you need t o invoke its Open m et hod
befor e the obj ect can link anot her object based on one of t he ot her SQL Server
.NET dat a provider classes, such as SqlCom m and, SqlDat aAdapt er, or
SqlDat aReader, to a SQL Server inst ance. I nvoke t he Close m et hod t o recover t he
resources for a SqlConnection obj ect when your solution no longer needs it . The
Close m et hod rolls back any pending transactions and releases the connect ion t o
the connect ion pool. The Dispose m et hod is also available for rem oving
connect ions, but it invokes t he Close m et hod and perform s other .NET
adm inist rat ive funct ions. Microsoft recom m ends t he Close m et hod for rem oving a
connect ion. Unclosed connect ions aren’t ret urned t o t he connect ion pool.
SqlCom m and and SqlDa t aReader Cla sses
One way to put a connect ion t o use is t o em ploy it along w it h the SqlCom m and
and SqlDat aReader obj ect s. A SqlDataReader object can maint ain an open
for ward- only, read-only connect ion w it h a SQL Server database. While t he
SqlDat aReader using a SqlConnect ion object is open, you cannot use the
SqlConnect ion obj ect for any other purpose except t o close t he connect ion.
Closing a SqlDat aReader obj ect releases it s associat ed SqlConnect ion obj ect for
ot her uses. The SqlDat aReader class doesn’t have a const ruct or st at em ent . You
declare t he SqlDat aReader obj ect w it h a Dim stat em ent and assign a result set
from a SqlCom mand obj ect t o a SqlDataReader wit h the Ex ecut eReader m et hod
of the SqlCom m and obj ect . Finally, invoke t he SqlDat aReader obj ect Read
m ethod t o open a r ow from t he resu lt set in t he SqlDataReader.
The SqlCom m and obj ect can ser ve m ult iple functions, including processing a T-
SQL st atem ent against a connect ion. When used in t his fashion, t he SqlCom m and
can take t wo argum ent s. The first can be a T- SQL dat a access stat em ent , such as
SELECT * FROM MyTable . The second SqlCom m and argum ent designat es t he
source connect ion for t he T- SQL st at em ent . For exam ple, you can use the nam e
of a SqlConnect ion obj ect , such as My SQLCnn1.
Figure 1 - 3 shows the rout e from a SQL Server data source t o a SqlDat aReader
obj ect . Alt hough t he SqlConnect ion and SqlCom m and obj ect s support t wo- way
interact ion wit h a dat a source, t he SqlDataReader obj ect allows read-only access
to t he result set from t he T- SQL st at em ent ser ving as an argum ent for a
SqlCom m and const ruct or. Because a SqlDat aReader obj ect cannot sp ecify it s ow n
dat a source, a SqlDat aReader obj ect m ust link t o a SqlConnection obj ect through
an interm ediat e SqlCom m and object .
Figure 1 - 3 . A schem at ic illu st ra t ing the r oute b y w hich a SqlDat a Reader
obj e ct ret urns valu e s to a n a pplication .
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.