Tải bản đầy đủ - 0 (trang)
Chapter 3. Querying and Retrieving Data

Chapter 3. Querying and Retrieving Data

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

UsingTable-ValuedTypesAsParameters

RetrievingaReturnValuefromaStoredProcedure

RetrievingaStoredProcedureOutputParameter

RaisingandHandlingStoredProcedureErrors

ExecutingaSQLServerScalar-ValuedFunction

ExecutingaSQLServerTable-ValuedFunction

QueryingaDataSetUsingLINQ

QueryingaSQLServerDatabaseUsingLINQ

RetrievingDatafromaTextFile

RetrievingDatafromaMicrosoftExcelWorkbook

QueryingDataAsynchronouslywithMessageQueuing



Recipe3.0.Introduction

ADO.NEThasbothconnectedanddisconnectedclasses.

Disconnectedclassesletyouaccessandmanipulateofflinethe

datayouretrievedusingtheconnectedclassesandlater

synchronizeitwiththeunderlyingdatasourceusingthe

connectedclasses.Thedisconnectedclassesincludethe

DataSet,DataTable,DataColumn,DataRow,DataView,

DataRelation,andConstraintclasses.Thedisconnected

classesarepartoftheADO.NETclassesinthe.NETFramework.

Connectedclassesletyouretrieveandupdatedatain

underlyingdatasources.TheseclassesincludetheConnection,

Command,DataReader,andDataAdapterclasses.Eachdata

providerisresponsibleforimplementingtheconnectedclasses.

Therecipesinthischapterdiscusscreating,workingwith,and

managingtheADO.NETconnectedobjects—thisincludes

executingqueries,retrievingresults,andretrievingand

navigatingresultssets.



AConnectionobjectisauniquesessionwiththedatasource.A

Connectionspecifiesnecessaryauthenticationinformation

neededtoconnecttoadatasource.TheConnectionobjectis

specifictothetypeofdatasource—forexample,the.NET

FrameworkdataproviderforSQLServerincludesthe

SqlConnectionclass.

ACommandexecutesSQLstatementsandstoredprocedures

againstthedatasourceusinganestablishedConnection.The

CommandTextpropertyoftheCommandclasscontainstheSQL

statementexecutedagainstthedatasource.TheCommand

objectisspecifictothetypeofdatasource—forexample,the

.NETFrameworkdataproviderforSQLServerincludesthe

SqlCommandobject.

ADataReaderprovidesforward-only,read-onlyaccesstoa

resultset.TheDataReaderoffersthebestperformancefor

accessingdatabyavoidingtheoverheadassociatedwiththe

DataSet.YoucreateaDataReaderbyexecutingthe

ExecuteReader()methodoftheCommandclass.Theschemaof

aDataReaderobjectisinferredfromthedatabaseschema.

TheConnectionobjectforaDataReaderremainsopenand

cannotbeusedforanyotherpurposewhiledataisbeing

accessed.ThismakestheDataReaderunsuitablefor

communicatingdataremotelybetweenapplicationtiers,or

interactingwiththedatadynamically.SincetheDataReader

readsaresultsetstreamdirectlyfromaconnection,thereisno

waytoknowthenumberofrecordsinaDataReader.Section

3.12demonstratestechniquesthatsimulatearecordcountfor

aDataReaderanddiscusseslimitationsofthetechniques.

ADataAdapterbridgestheconnectedclasseswiththe

disconnectedclassesbyretrievingdatafromadatasourceand

fillinga(disconnected)DataSet.TheDataAdapteralsoupdates

thedatasourcewithchangesmadetoadisconnectedDataSet.



TheDataAdapterusestheConnectionobjecttoconnectthe

datasourceandtheCommandobjecttoretrievedatafromand

resolvechangestothedatasource.TheDataAdapterobjectis

specifictothetypeofdatasource—forexample,the.NET

FrameworkdataproviderforSQLServerincludesthe

SqlDataAdapterobject.

Inadditiontorecipesforexecutingqueriesandretrieving

resultsusingtheconnectedclasses—DataAdapter,

Connection,Command,andDataReader—thischaptercovers

usingSQLServerandOracleparameterizedstatementsand

storedprocedurestoretrieveresultsetsandaswellasusing

inputandoutputparameters,andreturnvalues.



Chapter3.QueryingandRetrievingData

Introduction

ExecutingaQueryThatDoesNotReturnaResultSet

ExecutingaQueryThatReturnsaSingleValue

RetrievingaResultSetStreamUsingaDataReader

AccessingDataValuesinaDataReader

RetrievingaResultSetUsingaDataTableoraDataSet

AccessingDataValuesinaDataTableorDataSet

WorkingwithDatainaStronglyTypedDataSet

WorkingwithParent-ChildRelationsinaStronglyTypedDataSet

UsingaDataViewwithaStronglyTypedDataSet

TestingWhetheraQueryReturnsanEmptyResultSet

CountingRecordsMeetingCriteria

DeterminingtheNumberofRecordsReturnedinaDataReader

ExecutingaQueryThatReturnsMultipleResultSets

RetrievingSchemaandConstraintsforaDataSet

RetrievingHierarchicalData

NavigatingBetweenParentandChildTablesinanUntyped

DataSet

ExecutingaParameterizedQuery

RetrievingDataUsingaSQLServerStoredProcedure

RetrievingMultipleResultSetsUsingtheOracleProvider

PassingaNullValuetoaQueryParameter



UsingTable-ValuedTypesAsParameters

RetrievingaReturnValuefromaStoredProcedure

RetrievingaStoredProcedureOutputParameter

RaisingandHandlingStoredProcedureErrors

ExecutingaSQLServerScalar-ValuedFunction

ExecutingaSQLServerTable-ValuedFunction

QueryingaDataSetUsingLINQ

QueryingaSQLServerDatabaseUsingLINQ

RetrievingDatafromaTextFile

RetrievingDatafromaMicrosoftExcelWorkbook

QueryingDataAsynchronouslywithMessageQueuing



Recipe3.0.Introduction

ADO.NEThasbothconnectedanddisconnectedclasses.

Disconnectedclassesletyouaccessandmanipulateofflinethe

datayouretrievedusingtheconnectedclassesandlater

synchronizeitwiththeunderlyingdatasourceusingthe

connectedclasses.Thedisconnectedclassesincludethe

DataSet,DataTable,DataColumn,DataRow,DataView,

DataRelation,andConstraintclasses.Thedisconnected

classesarepartoftheADO.NETclassesinthe.NETFramework.

Connectedclassesletyouretrieveandupdatedatain

underlyingdatasources.TheseclassesincludetheConnection,

Command,DataReader,andDataAdapterclasses.Eachdata

providerisresponsibleforimplementingtheconnectedclasses.

Therecipesinthischapterdiscusscreating,workingwith,and

managingtheADO.NETconnectedobjects—thisincludes

executingqueries,retrievingresults,andretrievingand

navigatingresultssets.



AConnectionobjectisauniquesessionwiththedatasource.A

Connectionspecifiesnecessaryauthenticationinformation

neededtoconnecttoadatasource.TheConnectionobjectis

specifictothetypeofdatasource—forexample,the.NET

FrameworkdataproviderforSQLServerincludesthe

SqlConnectionclass.

ACommandexecutesSQLstatementsandstoredprocedures

againstthedatasourceusinganestablishedConnection.The

CommandTextpropertyoftheCommandclasscontainstheSQL

statementexecutedagainstthedatasource.TheCommand

objectisspecifictothetypeofdatasource—forexample,the

.NETFrameworkdataproviderforSQLServerincludesthe

SqlCommandobject.

ADataReaderprovidesforward-only,read-onlyaccesstoa

resultset.TheDataReaderoffersthebestperformancefor

accessingdatabyavoidingtheoverheadassociatedwiththe

DataSet.YoucreateaDataReaderbyexecutingthe

ExecuteReader()methodoftheCommandclass.Theschemaof

aDataReaderobjectisinferredfromthedatabaseschema.

TheConnectionobjectforaDataReaderremainsopenand

cannotbeusedforanyotherpurposewhiledataisbeing

accessed.ThismakestheDataReaderunsuitablefor

communicatingdataremotelybetweenapplicationtiers,or

interactingwiththedatadynamically.SincetheDataReader

readsaresultsetstreamdirectlyfromaconnection,thereisno

waytoknowthenumberofrecordsinaDataReader.Section

3.12demonstratestechniquesthatsimulatearecordcountfor

aDataReaderanddiscusseslimitationsofthetechniques.

ADataAdapterbridgestheconnectedclasseswiththe

disconnectedclassesbyretrievingdatafromadatasourceand

fillinga(disconnected)DataSet.TheDataAdapteralsoupdates

thedatasourcewithchangesmadetoadisconnectedDataSet.



TheDataAdapterusestheConnectionobjecttoconnectthe

datasourceandtheCommandobjecttoretrievedatafromand

resolvechangestothedatasource.TheDataAdapterobjectis

specifictothetypeofdatasource—forexample,the.NET

FrameworkdataproviderforSQLServerincludesthe

SqlDataAdapterobject.

Inadditiontorecipesforexecutingqueriesandretrieving

resultsusingtheconnectedclasses—DataAdapter,

Connection,Command,andDataReader—thischaptercovers

usingSQLServerandOracleparameterizedstatementsand

storedprocedurestoretrieveresultsetsandaswellasusing

inputandoutputparameters,andreturnvalues.



Recipe3.1.ExecutingaQueryThatDoes

NotReturnaResultSet

3.2.1.Problem

Youneedtoexecuteaqueryorcommandthatdoesnotreturn

aresultset.



3.2.2.Solution

UsetheExecuteNonQuery()methodoftheCommandobject.

TheT-SQLstatementtocreatethetable

ExecuteQueryNoResultSetusedinthissolutionisshownin

Example3-1.

Example3-1.StoredProcedure:Createtable

ExecuteQueryNoResultSet

USEAdoDotNet35Cookbook

GO

CREATETABLEExecuteQueryNoResultSet(

IdintNOTNULLPRIMARYKEY,

Field1nvarchar(50)NOTNULL,

Field2nvarchar(50)NOTNULL,

)

AndhereistheT-SQLstatementtoaddsampledatatothe

tableExecuteQueryNoResultSet:



















USEAdoDotNet35Cookbook

GO

INSERTINTOExecuteQueryNoResultSet

VALUES(1,'Field1.1','Field2.1');

INSERTINTOExecuteQueryNoResultSet

VALUES(2,'Field1.2','Field2.2');

INSERTINTOExecuteQueryNoResultSet

VALUES(3,'Field1.3','Field2.3');



ThesolutioncreatesaconnectionandexecutesaT-SQL

statementusingtheExecuteNonQuery()methodtodeletea

singlerowfromthetableExecuteQueryNoResultSet.The

numberofrowsaffectedisoutputtotheconsole.

TheC#codeinProgram.csintheproject

ExecuteQueryNoResultSetisshowninExample3-2.

Example3-2.File:Program.csfor

ExecuteQueryNoResultSetsolution

CodeView:

usingSystem;

usingSystem.Data;

usingSystem.Data.SqlClient;



namespaceExecuteQueryNoResultSet

{

classProgram

{

staticvoidMain(string[]args)

{

stringsqlConnectString=

"DataSource=(local);Integratedsecurity=SSPI;"

"InitialCatalog=AdoDotNet35Cookbook;";



stringsqlDelete="DELETEFROMExecuteQueryNoResul

"WHEREId=2";



//Createandexecuteacommandtodeletetherecor

//Id=2fromthetableExecuteQueryNoResultSet

SqlConnectionconnection=

newSqlConnection(sqlConnectString);

SqlCommandcommand=newSqlCommand(sqlDelete,conn

connection.Open();

introwsAffected=command.ExecuteNonQuery();



Console.WriteLine("{0}row(s)affected.",rowsAffec

Console.WriteLine("RecordwithId=2deleted.");

connection.Close();

Console.WriteLine("\nPressanykeytocontinue.");

Console.ReadKey();

}

}

}

























TheoutputisshowninFigure3-1.

Figure3-1.OutputforExecuteQueryNoResultSetsolution



3.2.3.Discussion

TheExecuteNonQuery()methodoftheCommandobject

executesaT-SQLstatement.Thenumberofrowsaffectedis

returnedforUPDATE,INSERT,andDELETEstatements.Allother

statementsreturn–1.YoucanusetheExecuteNonQuery()

methodtoexecuteT-SQLDDLstatementssuchasCREATE

TABLEorexecuteT-SQLcommandsthataffectdatasuchas

INSERT,UPDATE,andDELETE.Youdon'thavetostoreoruse

thereturnvalue—forexample,thecommandinthesolution

couldhavebeenwritten:





command.ExecuteNonQuery();



AlthoughtheExecuteNonQuery()doesnotreturnrows,output

andreturnvaluesmappedtoparametersarereturned.



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

Chapter 3. Querying and Retrieving Data

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

×