Tải bản đầy đủ - 0 (trang)
Chapter 1: Introduction to Database Programming with ADO.NET

Chapter 1: Introduction to Database Programming with ADO.NET

Tải bản đầy đủ - 0trang

Overview

ADatabaseisanorganizedcollectionofinformationthatisdividedinto

tables.Eachtableisfurtherdividedintorowsandcolumns;these

columnsstoretheactualinformation.Youaccessadatabaseusing

StructuredQueryLanguage(SQL),whichisastandardlanguage

supportedbymostdatabasesoftwareincludingSQLServer,Access,and

Oracle.

Inthischapter,you'llseeaC#programthatconnectstoaSQLServer

database,retrievesanddisplaysthecontentsstoredinthecolumnsofa

rowfromatable,andthendisconnectsfromthedatabase.You'llalsosee

programsthatconnecttoAccessandOracledatabases.

You'llalsolearnaboutMicrosoft'srapidapplicationdevelopment(RAD)

tool,VisualStudio.NET(VS.NET).VS.NETenablesyoutodevelop,

run,anddebugprogramsinanintegrateddevelopmentenvironment.

ThisenvironmentusesallthegreatfeaturesofWindows,suchasthe

mouseandintuitivemenus,andincreasesyourproductivityasa

programmer.

Inthefinalsectionsofthischapter,you'llseehowtousetheextensive

Microsoftdocumentationthatcomeswiththe.NETSoftware

DevelopmentKit(SDK)andVS.NET.You'llfindthisdocumentation

invaluableasyoubecomeanexpertwithADO.NETandC#.You'llalso

learnhowtousetheSQLServerdocumentation.

Featuredinthischapter:

Obtainingtherequiredsoftware

DevelopingyourfirstADO.NETprogram

ConnectingtoAccessandOracledatabases

IntroducingVisualStudio.NET

Usingthe.NETdocumentation



UsingtheSQLServerdocumentation



ObtainingtheRequiredSoftware

BeforeyoucandevelopC#programs,you'llneedtoinstalleitherthe

.NETSoftwareDevelopmentKit(SDK)orVS.NET.Youcandownload

the.NETSDKathttp://msdn.microsoft.com/downloads(search

fortheMicrosoft.NETFrameworkSoftwareDevelopmentKit).Youcan

purchaseatrialorfullcopyofVS.NETfromMicrosoftat

http://msdn.microsoft.com/vstudio.

Toinstallthe.NETSDK,runtheexecutablefileyoudownloadedand

followtheinstructionsonthescreentoinstallitonyourcomputer.To

installVS.NET,runthesetup.exefileonthediskandfollowthe

instructionsonthescreen.

You'llalsoneedacopyoftheSQLServerdatabasesoftware.Attimeof

writing,youcandownloadatrialversionofSQLServerfromMicrosoftat

http://www.microsoft.com/sql.Youcanalsopurchaseatrialor

fullcopyofSQLServerfromMicrosoft'sWebsite.

ThisbookusestheDeveloperEditionoftheSQLServer2000software

andusesadatabasenamedNorthwind.Thisdatabasecontainsthe

informationforthefictitiousNorthwindCompany,whichsellsfood

productstocustomers.Northwindisoneoftheexampledatabasesthat

youcaninstallwithSQLServer.CustomerinformationintheNorthwind

databaseisstoredinatablenamedCustomers;you'llseetheuseof

thistableintheexampleprogramlaterinthischapter.

Ifyoudon'twanttodownloadorpurchaseatrialversionofSQLServer,

the.NETSDK(andVS.NET)comeswithastand-alonedesktop

databaseserverknownastheMicrosoftSQLServer2000Desktop

Engine(MSDE2000).MSDE2000hasaversionoftheNorthwind

databasethatyoucanuseinsteadoftheSQLServerNorthwind

database-althoughyouwon'tgetallofthegraphicaladministrationtools

thatcomewithSQLServer.Ifyou'reusingthe.NETSDKandwantto

installMSDE2000,selectStart➣Microsoft.NETFrameworkSDK➣

SamplesandQuickStartTutorials.Ifyou'reusingVS.NETandwantto

installMSDE2000,runthesetup.exeprogramthatyouusetoinstallVS



.NETandselectMSDE2000asanewfeaturetoinstall.

Note YoucanlearnmoreaboutMSDE2000at

http://www.microsoft.com/sql/techinfo/development/2000/msde2000.asp



DevelopingYourFirstADO.NETProgram

Inthissectionyou'llplungeintoADO.NETprogrammingandseeaC#

programthatperformsthefollowingtasks:

1. ConnectstotheSQLServerNorthwinddatabase

2. RetrievesarowfromtheCustomerstable

3. Displaysthecolumnsfromtherow

4. Closesthedatabaseconnection

You'llbeintroducedtomanyconceptsinthissectionthatarefully

exploredinlaterchapters.Don'tbetooconcernedaboutallthedetailsof

theconceptsatthisstage;you'lllearnthosedetailsinthelaterchapters.

Listing1.1showstheexampleprogram,whichiscontainedinthefile

FirstExample.cs.

Listing1.1:FIRSTEXAMPLE.CS

/*

FirstExample.csillustrateshowto:

1.ConnecttotheSQLServerNorthwinddatabase.

2.RetrievearowfromtheCustomerstableusing

aSQLSELECTstatement.

3.Displaythecolumnsfromtherow.

4.Closethedatabaseconnection.

*/

usingSystem;

usingSystem.Data.SqlClient;

classFirstExample

{

publicstaticvoidMain()

{

try



{

//step1:createaSqlConnectionobjecttoconnecttoth

//SQLServerNorthwinddatabase

SqlConnectionmySqlConnection=

newSqlConnection(

"server=localhost;database=Northwind;uid=sa;pwd=sa"

);



//step2:createaSqlCommandobject

SqlCommandmySqlCommand=mySqlConnection.CreateCommand()



//step3:settheCommandTextpropertyoftheSqlCommand

//aSQLSELECTstatementthatretrievesarowfromtheC

mySqlCommand.CommandText=

"SELECTCustomerID,CompanyName,ContactName,Address"

"FROMCustomers"+

"WHERECustomerID='ALFKI'";



//step4:openthedatabaseconnectionusingthe

//Open()methodoftheSqlConnectionobject

mySqlConnection.Open();

//step5:createaSqlDataReaderobjectandcalltheExe

//methodoftheSqlCommandobjecttoruntheSELECTstat

SqlDataReadermySqlDataReader=mySqlCommand.ExecuteReade



//step6:readtherowfromtheSqlDataReaderobjectusi

//theRead()method

mySqlDataReader.Read();



//step7:displaythecolumnvalues

Console.WriteLine("mySqlDataReader[\"CustomerID\"]="+

mySqlDataReader["CustomerID"]);

Console.WriteLine("mySqlDataReader[\"CompanyName\"]="+

mySqlDataReader["CompanyName"]);

Console.WriteLine("mySqlDataReader[\"ContactName\"]="+

mySqlDataReader["ContactName"]);

Console.WriteLine("mySqlDataReader[\"Address\"]="+



mySqlDataReader["Address"]);



//step8:closetheSqlDataReaderobjectusingtheClose

mySqlDataReader.Close();



//step9:closetheSqlConnectionobjectusingtheClose

mySqlConnection.Close();

}

catch(SqlExceptione)

{

Console.WriteLine("ASqlExceptionwasthrown");

Console.WriteLine("Number="+e.Number);

Console.WriteLine("Message="+e.Message);

Console.WriteLine("StackTrace:\n"+e.StackTrace);

}

}

}



Note Youcandownloadallthesourcefilesfortheprogramsfeatured

inthisbookfromtheSybexWebsiteatwww.sybex.com.You'll

findinstructionsondownloadingthesefilesintheintroduction

ofthisbook.Onceyou'vedownloadedthefiles,youcanfollow

alongwiththeexampleswithouthavingtotypeintheprogram

listings.

Let'sgothroughthelinesinFirstExample.cs.Thefirstsetoflinesis

acommentthatindicateswhattheprogramdoes:

/*

FirstExample.csillustrateshowto:

1.ConnecttotheSQLServerNorthwinddatabase.

2.RetrievearowfromtheCustomerstableusing

aSQLSELECTstatement.

3.Displaythecolumnsfromtherow.

4.Closethedatabaseconnection.

*/



Thenexttwolinesindicatethenamespacesbeingreferencedinthe

programwiththeusingstatement:

usingSystem;

usingSystem.Data.SqlClient;

TheSystemnamespaceistherootnamespaceandisreferencedsothat

wecansimplyuseConsole.WriteLine()callsintheprogram,rather

thanthefullyqualifiedSystem.Console.WriteLine()call.The

System.Data.SqlClientnamespacecontainstheADO.NETclasses

forusewithSQLServer,includingtheSqlConnection,SqlCommand,

andSqlDataReaderclassesthatareusedlaterintheprogram.You'll

beintroducedtotheseclassesshortly,andyou'lllearnthefulldetailsof

theADO.NETclassesasyouprogressthroughthisbook.

Youhandleexceptionsthatmightbethrowninyourcodebyplacingthe

codewithinatry/catchblock.You'llnoticethattheninestepsare

placedwithinatry/catchblockintheMain()method,withthecatch

blockhandlingaSqlExceptionobjectthatmightbethrownbythecode

inthetryblock.You'lllearnmoreaboutthislaterinthesection

"HandlingExceptions"afterI'vediscussedtheninestepsinthefollowing

sections.



Step1:CreateaSqlConnectionObjecttoConnecttothe

Database

YouuseanobjectoftheSqlConnectionclasstoconnecttoaSQL

Serverdatabase.Step1intheMain()methodcreatesa

SqlConnectionobjectnamedmySqlConnectiontoconnecttothe

SQLServerNorthwinddatabase:

SqlConnectionmySqlConnection=

newSqlConnection(

"server=localhost;database=Northwind;uid=sa;pwd=sa"

);

ThestringpassedtotheSqlConnectionconstructorisknownasthe

connectionstringandcontainsthefollowingelements:



serverSpecifiesthenameofthecomputeronwhichSQL

Serverisrunning-localhostinthisexample;localhostisa

commonnamethatreferstothecomputeronwhichyourprogram

runs.Ifyourdatabaseisrunningonacomputerotherthanthe

oneyourprogramisrunningon,thenyou'llneedtoreplace

localhostwiththenameofthatcomputer.

databaseSpecifiesthenameofthedatabase-Northwindin

thisexample.

uidSpecifiesthenameofthedatabaseuseraccount-sainthis

example;saisacommondatabaseuseraccountusedbythe

databaseadministrator(DBA).Youcanuseanydatabaseuser

accountaslongasithasaccesstotheNorthwinddatabase.

pwdSpecifiesthepasswordfortheuser.Thepasswordforthesa

userinmydatabaseisalsosa.You'llneedtochangepwdtothe

passwordforyoursaaccount,orwhicheveraccountyou

specifiedinuid.

You'llneedtochangethesettingsofsomeorallofthepreviouselements

inyourconnectionstring.YoumightneedtospeakwithyourDBAtoget

thevariouselementsthatmakeupyourconnectionstring.Onceyou

havethecorrectvalues,youshouldmakethechangestotheconnection

stringinyourcopyofFirstExample.cs.

Note Adatabaseadministrator(DBA)isresponsibleforperforming

taskssuchasinstallingthedatabasesoftware,backingupthe

databases,andsoon.



Step2:CreateaSqlCommandObject

Step2createsaSqlCommandobjectnamedmySqlCommandthatis

usedlatertosendaSELECTstatementtothedatabaseforexecution.

SqlCommandmySqlCommand=mySqlConnection.CreateCommand();



Step3:SettheCommandTextPropertyoftheSqlCommand



Object

YouuseSQLtoworkwiththeinformationstoredinadatabase.SQLisan

industrystandardlanguagesupportedbySQLServer,Access,and

Oracle.YouusetheSQLSELECTstatementforretrievinginformation

fromadatabase.You'lllearnthebasicsofSQLinChapter3,

"IntroductiontotheStructuredQueryLanguage."

Step3setstheCommandTextpropertyofmySqlCommandcreatedinthe

previoussteptoaSELECTstatement.Thisstatementwillretrievethe

CustomerID,CompanyName,ContactName,andAddresscolumns

fromtherowintheCustomerstablewhoseCustomerIDisALFKI:

mySqlCommand.CommandText=

"SELECTCustomerID,CompanyName,ContactName,Address"+

"FROMCustomers"+

"WHERECustomerID='ALFKI'";



Step4:OpentheSqlConnectionObject

Step4opensthedatabaseconnectionusingtheOpen()methodofthe

SqlConnectionobjectcreatedinstep1:

mySqlConnection.Open();

Oncetheconnectiontothedatabaseisopen,youcansendcommands

tothedatabaseforexecution.



Step5:RuntheSELECTStatement

YouruntheSELECTstatementpreviouslysetinmySqlCommandby

callingtheExecuteReader()method.Thismethodreturnsa

SqlDataReaderobjectthatyouthenusetoreadtherowdatareturned

bytheSELECTstatement.

Step5createsaSqlDataReaderobjectandcallsthe

ExecuteReader()methodofmySqlCommandobjecttorunthe

SELECTstatement:



SqlDataReadermySqlDataReader=mySqlCommand.ExecuteReader();



Step6:ReadtheRowUsingtheSqlDataReaderObject

Step6readstherowinmySqlDataReaderusingtheRead()method:

mySqlDataReader.Read();



Step7:DisplaytheColumnValuesfromtheSqlDataReader

Object

YoucanreadthevalueforacolumnfrommySqlDataReaderby

passingthenameofthecolumninsquarebrackets.Forexample,

mySqlDataReader["CustomerID"]returnsthevalueofthe

CustomerIDcolumn.

Step7displaysthecolumnvaluesfortheCustomerID,CompanyName,

ContactName,andAddresscolumnvalues:

Console.WriteLine("mySqlDataReader[\"CustomerID\"]="+

mySqlDataReader["CustomerID"]);

Console.WriteLine("mySqlDataReader[\"CompanyName\"]="+

mySqlDataReader["CompanyName"]);

Console.WriteLine("mySqlDataReader[\"ContactName\"]="+

mySqlDataReader["ContactName"]);

Console.WriteLine("mySqlDataReader[\"Address\"]="+

mySqlDataReader["Address"]);



Step8:ClosetheSqlDataReaderObject

Whenyou'refinishedreadingrowsfromaSqlDataReaderobject,close

itusingtheClose()method.Step8callstheClose()methodfor

mySqlDataReader:

mySqlDataReader.Close();



Step9:ClosetheSqlConnectionObject



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

Chapter 1: Introduction to Database Programming with ADO.NET

Tải bản đầy đủ ngay(0 tr)

×