DAO's, RDO's and ADO's in Visual Basic Language
DAO's, RDO's and ADO's in Visual Basic Language
DAO's, RDO's and ADO's in Visual Basic Language
ADO.Net
Pretty much every application deals with data in some manner, whether that data comes from
memory, databases, XML files, text files, or something else. he location where we store the data can be
called as a !ata "ource or !ata "tore where a !ata "ource can be a file, database, or indexing server
etc.
Programming Languages cannot communicate with !ata "ources directly because each !ata
"ource adopts a different Protocol #set of rules$ for communication, so to overcome this problem long
bac% Microsoft has introduced intermediate technologies li%e &', (dbc and (ledb which wor%s li%e
bridge between the )pplications and !ata "ources to communicate with each other.
he Microsoft &et !atabase 'ngine is a database engine on which several Microsoft products
have been built. ) database engine is the underlying component of a database, a collection of information
stored on a computer in a systematic way. he first version of &et was developed in 1**2, consisting of
three modules which could be used to manipulate a database. &' stands for &oint 'ngine echnology,
sometimes being referred to as Microsoft &' 'ngine or simply &et. Microsoft )ccess and 'xcel uses &et
as their underlying database engine. (ver the years, &et has become almost synonymous with Microsoft
)ccess, to the extent where many people refer to a &et database as an +)ccess database+. M"
developed &et database system, a ,-based interface allowing applications to access that data, and a
selection of driver !LLs that allowed the same , interface to redirect input and output to databases.
.owever, &et did not use "/L0 the interface was in , and consisted of data structures and function calls.
(!1, #(pen !atabase ,onnectivity$ is a standard , programming language middleware )P2 for
accessing database management systems #!1M"$. (!1, accomplishes !1M" independence by using
an (!1, driver as a translation layer between the application and the !1M". he application uses
(!1, functions through an (!1, driver manager with which it is lin%ed, and the driver passes the 3uery
to the !1M". )n (!1, driver will be providing a standard set of functions for the application to use, and
implementing !1M"-specific functionality. )n application that can use (!1, is referred to as +(!1,-
compliant+. )ny (!1,-compliant application can access any !1M" for which a driver is installed. !rivers
exist for all ma4or !1M"s as well as for many other data sources li%e Microsoft 'xcel, and even for text or
,"5 files. (!1, was originally developed by Microsoft during the early 1**6s.
(L' !1 #(b4ect Lin%ing and 'mbedding, !atabase, sometimes written as (L'!1 or (L'-!1$,
an )P2 designed by Microsoft, allows accessing data from a variety of sources in a uniform manner. he
)P2 provides a set of interfaces implemented using the ,omponent (b4ect Model #,(M$. Microsoft
originally intended (L' !1 as a higher-level replacement for, and successor to, (!1,, extending its
feature set to support a wider variety of non-relational databases, such as ob4ect databases and
spreadsheets that do not necessarily implement "/L. (L' !1 is conceptually divided into consumers
and providers. he consumers are the applications that need access to the data, and the providers are
the software components that implement the interface and thereby provide the data to the consumer. )n
(L' !1 provider is a software component enabling an (L' !1 consumer to interact with a data source.
(L' !1 providers are ali%e to (!1, drivers or &!1, drivers for &ava. (L' !1 providers can be created
to access such simple data stores as a text file and spreadsheet, through to such complex databases as
(racle, Microsoft "/L "erver, and many others. 2t can also provide access to hierarchical data stores.
DAOs, RDOs and ADOs in Visual Basic Language:
5isual 1asic Language used !)(7s, 8!(7s and )!(7s for data source communication without
having to deal with the comparatively complex &' or (!1, or (L'!1 )P2.
21
!ata )ccess (b4ects is a deprecated general programming interface for database access on
Microsoft 9indows systems using &oint 'ngine echnology.
8emote !ata (b4ects #abbreviated 8!($ is the name of an obsolete data access application
programming interface primarily used in Microsoft 5isual 1asic applications on 9indows *: and later
operating systems. his includes database connection, 3ueries, stored procedures, result manipulation,
and change commits. 2t allowed developers to create interfaces that can directly interact with (pen
!atabase ,onnectivity #(!1,$ data sources on remote machines.
Microsoft;s )ctiveX !ata (b4ects #)!($ is a set of ,omponent (b4ect Model #,(M$ ob4ects for
accessing data sources. 2t provides a middleware layer between programming languages and (L' !1 #a
means of accessing data stores, whether they be databases or otherwise, in a uniform manner$. )!(
allows a developer to write programs that access data without %nowing how the database is implemented0
developers must be aware of the database for connection only. )!( is positioned as a successor to
Microsoft;s earlier ob4ect layers for accessing data sources, including 8!( #8emote !ata (b4ects$ and
!)( #!ata )ccess (b4ects$. )!( was introduced by Microsoft in (ctober 1**<.
ADO.NET Providers:
)!(.=' providers can be created to access such simple data stores as a text file and
spreadsheet, through to such complex databases as (racle, Microsoft "/L "erver, My"/L, Postgre"/L,
"/Lite, !12, "ybase )"', and many others. hey can also provide access to hierarchical data stores
such as email systems. .owever, because different data store technologies can have different
capabilities, every )!(.=' provider cannot implement every possible interface available in the
)!(.=' standard.
ADO.Net:
2t is a set of classes that expose data access services to the .=' programmer. )!(.='
provides functionality to developers writing managed code similar to the functionality provided to native
,(M developers by )!(. )!(.=' provides consistent access to data sources such as Microsoft "/L
"erver, as well as data sources exposed through (L' !1 and XML. !ata-sharing consumer applications
can use )!(.=' to connect to these data sources and retrieve, manipulate, and update data. 2t is an
integral part of the .=' >ramewor%, providing access to relational data, XML, and application data.
)!(.=' supports a variety of development needs, including the creation of front-end database clients
and middle-tier business ob4ects used by applications or 2nternet browsers. )!(.=et provides libraries for
!ata "ource communication under the following namespaces?
"ystem.!ata
"ystem.!ata.(dbc
"ystem.!ata.(ledb
"ystem.!ata."3l,lient
"ystem.!ata.(racle,lient
21
Note: "ystem.!ata, "ystem.!ata.(ledb, "ystem.!ata."3l,lient and "ystem.!ata.(dbc namespaces are
under the assembly "ystem.!ata.dll whereas "ystem.!ata.(racle,lient is under
"ystem.!ata.(racle,lient.dll assembly.
Sste!.Data: types of this namespace are used for holding and managing of data on client machines.
his namespace contains following set of classes in it? !ata"et, !ataable, !ata,olumn, !ata8ow,
!ata5iew, !ata8elation etc.
Sste!.Data.Od"c: types of this namespace can communicate with any !ata "ource li%e files,
databases, and indexing servers etc. using @n-Managed (dbc !rivers.
Sste!.Data.Oled": types of this namespace can communicate with any !ata "ource li%e files,
databases, and indexing servers etc. using (ledb Providers #@n-Managed ,(M Provider$.
Sste!.Data.S#l$lient: types of this namespace can purely communicate with "3l "erver database only
using "3l,lient Provider #Managed )!(.=et Provider$.
Sste!.Data.Oracle$lient: types of this namespace can purely communicate with (racle database only
using (racle,lient Provider #Managed )!(.=et Provider$.
)ll the above A namespaces contains same set of types as following? ,onnection, ,ommand,
!ata8eader, !ata)dapter, ,ommand1uilder etc, but here each class is referred by prefixing with their
namespace before the class name to discriminate between each other as following?
(ledb,onnection (ledb,ommand (ledb!ata8eader (ledb!ata)dapter
(ledb,ommand1uilder
"3l,onnection "3l,ommand "3l!ata8eader "3l!ata)dapter
"3l,ommand1uilder
(racle,onnection (racle,ommand (racle!ata8eader (racle!ata)dapter
(racle,ommand1uilder
(dbc,onnection (dbc,ommand (dbc!ata8eader (dbc!ata)dapter
(dbc,ommand1uilder
Per%or!ing O&erations on a DataSource: 'ach and every operation we perform on a !ata "ource
involves in B steps, li%e?
'stablishing a connection with data source.
"ending re3uest to data source as a s3l statement.
,apturing the results given by data source.
Esta"lis'ing a $onnection (it' Data Source:
2t;s a process of opening a channel for communication between )pplication and !ata "ource that
is present on a local or remote machine to perform any operations. o open the channel for
communication we can use the ,onnection class.
$onstructors o% t'e $lass:
,onnection#$
,onnection#string ,onnection"tring$
Note: ,onnection"tring is a collection of attributes that are used for connecting with a !ata"ource, those
are?
Provider
!ata "ource
@ser 2d and Password
21
!atabase or 2nitial ,atalog
rustedC,onnection or 2ntegrated "ecurity
!"=
Provider: as discussed earlier provider is re3uired for connecting with any data source;s, we have a
different provider available for each data source.
(racle Msdaora "3l "erver "3l(ledb
M"-)ccess or M"-'xcelMicrosoft.&et.(ledb.A.6 M"-2ndexing "erver Msidxs
Data Source: it is the name of target machine to which we want to connect with but it is optional when the
data source is on a local machine.
)ser *d and Pass(ord: as db;s are secured places for storing data, to connect with them we re3uire a
valid user id and password.
(racle? "cottDtiger "3l "erver? "aDEpwdF
Data"ase or *nitial $atalog: these attributes are used while connecting with "3l "erver !atabase to
specify the name of database we want to connect with.
Trusted+$onnection or *ntegrated Securit: these attributes are also used while connecting with "3l
"erver !atabase only to specify that we want to connect with the "erver using 9indows )uthentication.
2n this case we should not again use @ser 2d and Password attributes.
DSN: this attribute is used to connect with data sources by using (dbc !rivers.
$onnection String %or Oracle: +ProviderGMsdaora0@ser 2dG"cott0PasswordGtigerH0!ata
"ourceGEserverFI+
$onnection String %or S#l Server: +ProviderG"3l(ledb0@ser 2dG"a0PasswordGEpwdF0!atabaseGEdb
nameFH0!ata "ourceGEserverFI+
Note: in case of 9indows )uthentication in place of @ser 2d and Password attributes we need to use
2ntegrated "ecurity G ""P2 #"ecurity "upport Provider 2nterface$ or rustedC,onnection G rue.
,e!"ers o% $onnection class:
1. O&en-.: a method which opens a connection with data source.
2. $lose-.: a method which closes the connection that is open.
B. State: an enumerated property which is used to get the status of connection.
A. $onnectionString: a property with is used to get or set a connection string which is associated
with the connection ob4ect.
T'e O"/ect o% class $onnection can "e created in an o% t'e %ollo(ing (as:
Connnection con = new Connection(); con.ConnectionString = "<connection string>";
or
Connection con = new Connection("<connection string>");
Testing t'e &rocess o% esta"lis'ing a connection: open a new pro4ect of type 9indows >orms
)pplication and name it as !1(perations. Place 2 buttons on the form and set their caption as J,onnect
with (racle using (L'!1 ProviderK and J,onnect with "3l "erver using (L'!1 ProviderK. =ow go to
code view and write the following code?
using "ystem.!ata.(le!b0
Declarations: OledbConnection ocon, scon;
Under Connect with Oracle using OLEDB Provider:
ocon = new OleDbConnection(Provider=Msdor;!ser "d=Scott;Pssword=tiger;Dt
So#rce=<server>");
ocon.O$en(); Messge%o&.S'ow(ocon.Stte.(oString()); ocon.Close();
Messge%o&.S'ow(ocon.Stte.(oString());
21
Under Connect with Sql Server using Oledb Provider:
scon = new OleDbConnection(); scon.ConnectionString =
"Provider=S)lOledb;!ser "d=S;Pssword=<$wd>;Dtbse=Mster;Dt So#rce=<server>";
scon.O$en(); Messge%o&.S'ow(scon.Stte.(oString()); scon.Close();
Messge%o&.S'ow(scon.Stte.(oString());
Sending re#uest to Data Source as a S#l State!ent: 2n this process we send a re3uest to !ata "ource
by specifying the type of action we want to perform using a "3l "tatement li%e "elect, 2nsert, @pdate, and
!elete or by calling a "tored Procedure. o send and execute those statements on data source we use
the class ,ommand.
$onstructors o% t'e class: ,ommand#$ ,ommand#string ,ommandext,
,onnection con$
Note: ,ommandext means it can be any "3l "tmt li%e "elect or 2nsert or @pdate or !elete "tmts or
"tored Procedure =ame.
Pro&erties o% $o!!and $lass:
1. ,onnection? sets or gets the connection ob4ect associated with command ob4ect.
2. ,ommandext? sets or gets the s3l statement or "P name associated with command ob4ect.
T'e o"/ect o% class $o!!and can "e created in an o% t'e %ollo(ing (as:
,ommand cmd G new ,ommand#$0 cmd.,onnection G EconF0 cmd.,ommandext G +Es3l stmt or "P
=ameF+0
or
,ommand cmd G new ,ommand#+Es3l stmt or "P =ameF+, con$0
,et'ods o% $o!!and class:
'xecute8eader#$ -F !ata8eader
'xecute"calar#$ -F ob4ect
'xecute=on/uery#$ -F int
Note: after creating ob4ect of ,ommand class we need to call any of these B methods to execute that
statement.
@se E0ecuteReader-. method when we want to execute a "elect "tatement that returns data as
rows and columns. he method returns an ob4ect of class !ata8eader which holds data that is retrieved
from data source in the form of rows and columns.
@se E0ecuteScalar-. method when we want to execute a "elect "tatement that returns a single
value result. he method returns result of the 3uery in the form of an ob4ect.
@se E0ecuteNon1uer-. method when we want to execute any "/L statement other than
select, li%e 2nsert or @pdate or !elete etc. he method returns an integer that tells the no. of rows affected
by the statement.
Note: he above process of calling a suitable method to capture the results is our third step i.e. capturing
the results given by data source.
Accessing data %ro! a DataReader: !ata8eader is a class which can hold data in the form of rows and
columns, to access data from !ata8eader it provides the following methods?
1. Let=ame#int columnindex$ -F string
8eturns name of the column for given index position.
2. 8ead#$ -F bool
21
Moves record pointer from the current location to next row and returns a bool value which tells whether
the row to which we have moved contains data in it or not, that will be true if data is present or false if
data is not present.
B. Let5alue#int coloumnindex$ -F ob4ect
@sed for retrieving column values from the row to which pointer was pointing by specifying the column
index position. 9e can also access the row pointed by pointer in the form of a single dimensional array
also, either by specifying column index position or name, as following?
E!8FHcolumn indexI -F ob4ect
E!8FHcolumn nameI -F ob4ect
)dd a new 9indows >orm under the pro4ect and design it as following?
using "ystem.!ata.(le!b0
Declarations: (le!b,onnection con0 (le!b,ommand cmd0 (le!b!ata8eader dr0
)nder 2or! Load: conGnew (le!b,onnection#+ProviderGMsdaora0@ser 2dG"cott0PasswordGtiger+$0
cmd G new (le!b,ommand#+"elect !eptno, !name, Loc >rom !ept+, con$0 con.(pen#$0 dr G
cmd.'xecute8eader#$0
label1.ext G dr.Let=ame#6$0 label2.ext G dr.Let=ame#1$0 labelB.ext G dr.Let=ame#2$0 "how!ata#$0
private void S'o(Data-. M
if#dr.8ead#$$ M
text1ox1.ext G dr.Let5alue#6$.o"tring#$0 text1ox2.ext G drH1I.o"tring#$0 text1oxB.ext G
drH+Loc+I.o"tring#$0
N
else Message1ox."how#+Last 8ecord+$0
N
)nder Ne0t Button: "how!ata#$0
)nder $lose Button: if#con."tate OG ,onnection"tate.,losed$ M con.,lose#$0 N this.,lose#$0
3or4ing (it' S#l Server
"3l "erver is a collection of databases, where a database is again collection of various ob4ects
li%e tables, views, procedures etc.0 users of "3l "erver can be owner of 1 or more databases at a time, so
while connecting with s3l server from a .net application within the connection string we need to specify
name of the database we want to connect either by using !atabase or 2nitial ,atalog attributes.
"3l "erver provides 2 different modes of authentication for connecting with the !1 "erver those are?
5. 3indo(s Aut'entication
6. S#l Server Aut'entication
9hen a user connects through windows authentication, "3l "erver validates the account name
and password using the windows principal to%en in the operating system0 this means that the user identity
is confirmed by windows, "3l "erver does not as% for the password and does not perform the identity
validation. 9hen using "3l "erver authentication, logins are created in s3l server that is not based on
windows user accounts, both the user name and password are created by using s3l server and stored in
s3l server database. @sers connecting with s3l server authentication must provide their credentials every
time they connect with !1 "erver.
21
Note: if we want to connect using windows authentication mode, within the connection string in the place
of @ser 2d and Password attributes use JrustedC,onnectionGrueK or J2ntegrated "ecurityG""P2K
attributes.
$onnecting String %or S#l Server Aut'entication:
Provider=S)lOledb;!ser "d=S;Pssword=<$wd>;Dtbse=<dbn*e>+;Dt So#rce=<server
n*e>,-
$onnecting String %or 3indo(s Aut'entication:
Provider=S)lOledb;(r#sted.Connection=(r#e;Dtbse=<dbn*e>+;Dt So#rce=<server
n*e>,-
Or
Provider=S)lOledb;"ntegrted Sec#rit/=SSP";Dtbse=<dbn*e>+;Dt So#rce=<server
n*e>,-
$reating a data"ase on S#l Server:
Lo to "tart Menu -F Programs -F M" "3l "erver -F "3l "erver Management "tudio, open it and
provide the authentication details to login. (nce the studio is opened in the L." we find a window J(b4ect
'xplorerK, in that right clic% on the node !atabases, select J=ew !atabaseK that opens a window as%ing
for the name, enter the name as? E!1 =ameF, clic% o% which adds the database under databases node.
=ow expand the database node, right clic% on ables node and select J=ew ableK which opens a
window as%ing for column names and data types enter the following?
Eno (Int! Ena"e (#archar! $ob (#archar! Salar% (&one%! Photo (I"age! Status (Bit
=ow select 'no ,olumn, right clic% on it and select the option J"et Primary PeyK and ma%e it as
an identity or %ey column of the table. "elect "tatus column, go to its properties in the bottom and set
J!efault value or 1indingK property as 1, which ta%es the default value for status column as true. ,lic% on
the save button at top of the studio which will prompt for table name enter name as J'mployeeK and clic%
O4 which adds the table under tables node. =ow right clic% on the table created and select J'ditK which
opens a window, in that enter the data we want ignoring Photo and "tatus columns. ,lose the studio.
Note: 9e can connect with "3l "erver from .net applications either by using (ledb or "3l,lient classes
also. 2f use "3l,onnection or (racle,onnection classes to connect with databases then connection string
doesn7t re3uire Provider attribute to be specified as these classes are designed specific for those
databases.
)dd a new form in the pro4ect and design it as following?
using "ystem.!ata."3l,lient0
Declarations: "3l,onnection con0 "3l,ommand cmd0 "3l!ata8eader dr0 string "3l"tr0
"et 8ead-only Property as
rue
"et 'nabled Property as
>alse
21
)nder 2or! Load: con G new "3l,onnection#+@ser 2dG"a0PasswordGEPwdF0!atabaseGE!1
=ameF0!ata "ourceGE"erver =ameF+$0 cmd G new "3l,ommand#$0 cmd.,onnection G con0 con.(pen#$0
Load!ata#$0
&rivate void LoadData-. M
cmd.,ommandext G +"elect 'no, 'name, &ob, "alary >rom 'mployee (rder 1y 'no+0
dr G cmd.'xecute8eader#$0 "how!ata#$0
N
&rivate void S'o(Data-. M
if #dr.8ead#$$ M
text1ox1.ext G drH6I.o"tring#$0 text1ox2.ext G drH1I.o"tring#$0
text1oxB.ext G drH2I.o"tring#$0 text1oxA.ext G drHBI.o"tring#$0
N
else M Message1ox."how#+=o data exists.+$0 N
N
)nder Ne0t Button: "how !ata#$0
)nder Ne( Button:
text1ox1.ext G text1ox2.ext G text1oxB.ext G text1oxA.ext G ++0
dr.,lose#$0 cmd.,ommandext G +"elect 2s=ull#Max#'no$, 1666$ Q 1 >rom 'mployee+0
text1ox1.ext G cmd.'xecute"calar#$.o"tring#$0 btn2nsert.'nabled G true0 text1ox2.>ocus#$0
&rivate void E0ecuteD,L-. M
!ialog8esult d G Message1ox."how#J)re you sure of executing the below "3l "tatementRSnSn+ Q "3l"tr,
+,onfirmation+, Message1ox1uttons.Tes=o, Message1ox2con./uestion$0
if #d GG !ialog8esult.Tes$ M
cmd.,ommandext G "3l"tr0 int count G cmd.'xecute=on/uery#$0
if #count F 6$ Message1ox."how#+"tatement executed successfully+$0
else Message1ox."how#+"tatement failed execution+$0
Load!ata#$0
N N
)nder *nsert Button:
"3l"tr G +2nsert 2nto 'mployee #'no, 'name, &ob, "alary$ 5alues#+ Q text1ox1.ext Q +, ;+ Q text1ox2.ext
Q +;, ;+ Q text1oxB.ext Q +;, + Q text1oxA.ext Q +$+0 'xecute!ML#$0 btn2nsert.'nabled G false0
or
"3l"tr G "tring.>ormat#+2nsert 2nto 'mployee #'no, 'name, &ob, "alary$ 5alues#M6N, ;M1N;, ;M2N;, MBN$+,
text1ox1.ext, text1ox2.ext, text1oxB.ext, text1oxA.ext$0 'xecute!ML#$0 btn2nsert.'nabled G false0
)nder )&date Button:
"3l"tr G +@pdate 'mployee "et 'nameG;+ Q text1ox2.ext Q +;, &obG;+ Q text1oxB.ext Q +;, "alaryG+ Q
text1oxA.ext Q + 9here 'noG+ Q text1ox1.ext0 dr.,lose#$0 'xecute!ML#$0 or
"3l"tr G "tring.>ormat#+@pdate 'mployee "et 'nameG;M6N;, &obG;M1N;, "alaryGM2N 9here 'noGMBN+,
text1ox2.ext, text1oxB.ext, text1oxA.ext, text1ox1.ext$0 dr.,lose#$0 'xecute!ML#$0
)nder Delete Button:
"3l"tr G +!elete >rom 'mployee 9here 'noG+ Q text1ox1.ext0 dr.,lose#$0 'xecute!ML#$0 or
"3l"tr G "tring.>ormat#+!elete >rom 'mployee 9here 'noGM6N+, text1ox1.ext$0 dr.,lose#$0
'xecute!ML#$0
)nder $lose Button: if #con."tate OG ,onnection"tate.,losed$ M con.,lose#$0 N this.,lose#$0
DataReader: it;s a class designed for holding the data on client machines in the form of 8ows and
,olumns.
2eatures o% DataReader:
21
1. >aster access to data from the data source as it is connection oriented.
2. ,an hold multiple tables in it at a time. o load multiple tables into a !ata8eader pass multiple
select statements as arguments to command separated by a semi-colon.
'.g.? ,ommand cmd G new ,ommand#+"elect U >rom "tudent0"elect U >rom eacher+, con$0
!ata8eader dr G cmd.'xecute8eader#$0
Note: use =ext8esult#$ method on data reader ob4ect to navigate from current table to next table.
'.g.? dr.=ext8esult#$0
Dra("ac4s o% DataReader:
1. )s it is connection oriented re3uires a continuous connection with data source while we are
accessing the data, so there are chances of performance degradation if there are more no. of
clients accessing data at the same time.
2. 2t gives forward only access to the data i.e. allows going either to next record or table but not to
previous record or table.
B. 2t is a read only ob4ect which will not allow any changes to data that is present in it.
Dis7$onnected Arc'itecture? )!(.=et provides 2 different models for accessing data from !ata
"ources?
1. ,onnection (riented )rchitecture 2. !isconnected )rchitecture
2n the first case we re3uire a continuous connection with the data source for accessing data from it,
in this case we use !ata8eader class for holding the data on client machines, where as in the 2nd case
we don7t re3uire a continuous connection with data source for accessing of the data from it, we re3uire
the connection only for loading the data from data source and here !ata"et class is used for holding the
data on client machines.
3or4ing (it' DataSet
DataSet: 2t;s a class present under "ystem.!ata namespace designed for holding and managing of data
on client machines apart from !ata8eader. !ata"et class provides the following features?
1. 2t is designed in disconnected architecture which doesn;t re3uire any permanent connection with
the data source for holding of data.
2. 2t provides scrollable navigation to data which allows us to move in any direction i.e. either top to
bottom or bottom to top.
B. 2t is updatable i.e. changes can be made to data present in it and those changes can be sent
bac% to !1.
A. !ata"et is also capable of holding multiple tables in it.
:. 2t provides options for searching and sorting of data that is present under it.
<. 2t provides options for establishing relations between the tables that are present under it.
)sing DataSet8s: he class which is responsible for loading data into !ata8eader from a !ata"ource is
,ommand, in the same way !ata)dapter class is used for communication between !ata"ource and
!ata"et.
DataReader 97 $o!!and 7: DataSource
DataSet 97: DataAda&ter 97: DataSource
$onstructors o% DataAda&ter class:
!ata)dapter#string selectcommand, ,onnection con$ !ata)dapter#,ommand cmd$
Note: selectcommand means it can be a select statement or a "tored Procedure which contains a select
statement.
21
,et'ods o% DataAda&ter:
>ill#!ata"et ds, string table=ame$ @pdate#!ata"et ds, string table=ame$
!ata)dapter7s can internally contain A ,ommands under them associated with a single table, those are?
-"elect ,ommand -2nsert ,ommand -@pdate ,ommand -!elete
,ommand
9hen we call >ill method on !ata)dapter following actions ta%es place internally?
(pens a connection with the !ata "ource.
'xecutes the "elect,ommand present under it on the !ata"ource and loads data from table to
!ata"et.
,loses the connection.
)s we are discussing !ata"et is updatable, we can ma%e changes to the data that is loaded into it
li%e adding, modifying and deleting of records, after ma%ing changes to data in !ata"et if we want to send
those changes bac% to !ata"ource we need to call @pdate method on !ata)dapter, which performs the
following?
8e-opens a connection with the !ata "ource.
,hanges that are made to data in !ata"et will be sent bac% to corresponding table, where in this
process it will ma%e use of 2nsert, @pdate and !elete commands of !ata)dapter.
,loses the connection.
Accessing data %ro! DataSet: !ata 8eader7s provides pointer based access to the data, so we can get
data only in a se3uential order whereas !ata"et provides index based access to the data, so we can get
data from any location randomly. !ata"et is a collection of tables where each table is represented as a
class !ataable and identified by its index position or name. 'very !ataable is again collection of 8ows
and collection of ,olumns where each row is represented as a class !ata8ow and identified by its index
position and each column is represented as a class !ata,olumn and identified by its index position or
name.
)ccessing a !ataable from !ata"et? EdatasetF.ablesHindexI or EdatasetF.ablesHnameI
'.g.? ds.ablesH6I or ds.ablesH+'mployee+I
)ccessing a !ata8ow from !ataable? EdatatableF.8owsHindexI
'.g.? ds.ablesH6I.8owsH6I
)ccessing a !ata,olumn from !ataable? EdatatableF.,olumnsHindexI or
EdatatableF.,olumnsHnameI
'.g.? ds.ablesH6I.,olumnsH6I or ds.ablesH6I.,olumnsH+'no+I
)ccessing a ,ell from !ataable? EdatatableF.8owsHrowIHcolI
21
'.g.? ds.ablesH6I.8owsH6IH6I or ds.ablesH6I.8owsH6IH+'no+I
)dd a new form in the pro4ect design it as below, then add reference of Microsoft.5isual1asic
assembly from .=et tab of add reference window and write the code?
#sing S/ste*.Dt.S)lClient; #sing Microso0t.1is#l%sic;
Declarations: S)lConnection con; S)lDt2d$ter d; s)lCo**nd%#ilder cb; DtSet ds; int rno = 3;
Under 'or" Load:
con = new S)lConnection("!ser "d=S;Pssword=<$wd>;Dtbse=<D% 4*e>;Dt So#rce=<Server
4*e>");
d = new S)lDt2d$ter("Select 5no, 5n*e, 6ob, Slr/ 7ro* 5*$lo/ee Order %/ 5no", con);
ds = new DtSet(); d.MissingSc'e*2ction = MissingSc'e*2ction.2dd8it'9e/;
d.7ill(ds, "5*$lo/ee"); S'owDt();
(rivate void ShowData( :
te&t%o&;.(e&t=ds.(bles+3,.<ows+rno,+3,.(oString(); te&t%o&=.(e&t=ds.(bles+3,.<ows+rno,+;,.(oString();
te&t%o&>.(e&t=ds.(bles+3,.<ows+rno,+=,.(oString(); te&t%o&?.(e&t=ds.(bles+3,.<ows+rno,+>,.(oString();
@
Under 'irst Button: rno = 3; S'owDt();
Under Prev Button:
i0 (rno > 3) :
rno A= ;; i0 (ds.(bles+3,.<ows+rno,.<owStte == Dt<owStte.Deleted) :
Messge%o&.S'ow("Deleted row dt cnnot be ccessed."); ret#rn;
@
S'owDt();
@ else
Messge%o&.S'ow("7irst record o0 t'e tble.");
Under )e*t Button:
i0 (rno < ds.(bles+3,.<ows.Co#nt A ;) :
rno B= ;; i0 (ds.(bles+3,.<ows+rno,.<owStte == Dt<owStte.Deleted) :
Messge%o&.S'ow("Deleted row dt cnnot be ccessed."); ret#rn;
@
S'owDt();
@
else
Messge%o&.S'ow("Cst record o0 t'e tble.");
Under Last Button: rno = ds.(bles+3,.<ows.Co#nt D ;; S'owDt();
Under )ew Button:
te&t%o&;.(e&t = te&t%o&=.(e&t = te&t%o&>.(e&t = te&t%o&?.(e&t = -;
int inde& = ds.(bles+3,.<ows.Co#nt D ;;
int eno = Convert.(o"nt>=(ds.(bles+3,.<ows+inde&,+3,) B ;;
te&t%o&;.(e&t = eno.(oString(); te&t%o&=.7oc#s();
"et 8ead-only Property as
rue
21
Adding a DataRo( to DataTa"le o% DataSet:
o add a !ata8ow to the !ataable of !ata"et adopt the following process?
1. ,reate a new row by calling the =ew8ow#$ method on !ataable.
2. )ssign values to the new row by treating it as a single dimensional array.
B. ,all the 8ows.)dd method on !ataable and add the row to !ata8ow,ollection.
Under Insert Button:
Dt<ow dr = ds.(bles+3,.4ew<ow();
dr+3, = te&t%o&;.(e&t; dr+;, = te&t%o&=.(e&t; dr+=, = te&t%o&>.(e&t; dr+>, = te&t%o&?.(e&t;
ds.(bles+3,.<ows.2dd(dr); rno = ds.(bles+3,.<ows.Co#nt D ;;
Messge%o&.S'ow("Dt<ow dded to Dt(ble o0 DtSet.");
)&dating a DataRo( in DataTa"le o% DataSet:
o update an existing !ata8ow in !ataable of !ata"et we need to re-assign the modified
values bac% to the !ata8ow in data table, so that the old values get modified with new values.
Under U(date Button E
ds.(bles+3,.<ows+rno,+;, = te&t%o&=.(e&t; ds.(bles+3,.<ows+rno,+=, = te&t%o&>.(e&t;
ds.(bles+3,.<ows+rno,+>, = te&t%o&?.(e&t; Messge%o&.S'ow("Dt<ow #$dted in Dt(ble.");
Deleting a DataRo( in DataTa"le o% DataSet: o delete an existing !ata8ow in !ataable of !ata"et
call !elete#$ method pointing to the row that has to be deleted on !ata8ow,ollection.
Under Delete Button:
ds.(bles+3,.<ows+rno,.Delete(); Messge%o&.S'ow("Dt<ow deleted in Dt(ble o0 DtSet.");
Saving c'anges !ade in DataTa"le o% DataSet "ac4 to DataBase:
2f we want to save changes made in !ataable of !ata"et bac% to !ata 1ase we need to call
@pdate method on !ata)dapter by passing the !ata"et which contains modified values as a parameter.
2f @pdate method of !ata)dapter has to wor% it should contain the B commands under it i.e. 2nsert,
@pdate and !elete, these B commands have to be written by the programmers explicitly or can be
generated implicitly with the help of ,ommand1uilder class. ,ommand1uilder class constructor if given
with !ata)dapter that contains a "elect,ommand in it will generate the re3uired B commands.
Note: ,ommand1uilder can generate update and delete commands for a given select command only if
the table contains Primary Pey ,onstraints on it.
Under Save +o DB Button:
cb = new S)lCo**nd%#ilder(d); d.!$dte(ds, "5*$lo/ee"); Messge%o&.S'ow("Dt sved to D%
Server");
Under Close Button: t'is.Close();
Searc'ing %or a DataRo( in DataTa"le o% DataSet:
o search for a !ata8ow in !ataable of !ata"et call >ind method on !ata8ow,ollection this
searches for the !ata8ow on Primary Pey ,olumn#s$ of table and returns a 8ow.
7ind(ObFect Ge/) A> Dt<ow 7ind(ObFect+, Ge/s) A> Dt<ow
@se the first method if the primary %ey constraint is present on a single column or else use the
second method if it is a composite primary %ey.
Note: if the >ind method has to wor% we need to first load the Primary Pey information of table into
!ata"et by setting the property value as J)dd9ithPeyK for Missing"cheman)ction of !ata)dapter.
Under Search Button:
string vl#e = "nterction."n$#t%o&("5nter 5*$lo/ee 4o.", "5*$lo/ee Serc'", "", ;H3, ;H3);
i0 (vl#e.(ri*().Cengt' > 3) :
int eno = int.Prse(vl#e); Dt<ow dr = ds.(bles+3,.<ows.7ind(eno);
i0 (dr I= n#ll) :
21
te&t%o&;.(e&t = dr+3,.(oString(); te&t%o&=.(e&t = dr+;,.(oString();
te&t%o&>.(e&t = dr+=,.(oString(); te&t%o&?.(e&t = dr+>,.(oString();
@
else : Messge%o&.S'ow("5*$lo/ee does not e&ists 0or given 5*$lo/ee 4o."); @
@
$on%iguration 2iles
9hile developing applications if there are any values in application which re3uires changes in
future, should not be hard coded i.e. should not be maintained as static values within the application,
because if any changes are re3uired for those values in future client will not be able to ma%e changes
because they will not have the source code of application for modification. o overcome this problem we
need to identify those values and put them under a special file %nown as ,onfiguration >ile, it7s an XML
file which stores values in it in the form of PeyD5alue pairs. he values that are present under
configuration file can be read from applications in runtime. 9e store values li%e ,ompany =ame,
)ddress, Phone =o, >ax =o, connection strings etc., in these files. 9hen an application is installed on the
client machines along with it the configuration file also will be installed there and because the
configuration file is a text file clients can edit those files and ma%e modification to the values under them
at any time and those values will be ta%en into the application for execution.
Note: =ame of configuration file will be Japp.configK, and it will be available implicitly under the pro4ect. 2f
wor%ing with below versions of 5" 2612 it should be explicitly added under the pro4ect, but before adding
a configuration file under a pro4ect verify the availability of it in the pro4ect and if not present then only add
it. o add a configuration file in the pro4ect open the J)dd =ew 2temK window and select the option
J)pplication ,onfiguration >ileK which adds a file with the name as app.config.
Storing values under con%iguration %ile: 1y default the file comes with a tag
EconfigurationFEDconfigurationF, all the values must be present under that tag only by maintaining them
under different sections as following?
Eapp"ettingsF
Eadd %eyG+,name+ valueG+=aresh 2 echnologies+DF
Eadd %eyG+)ddress+ valueG+)meerpet, .yderabad - BV+DF
Eadd %eyG+Phone+ valueG+2BWA<<<<+DF
Eadd %eyG+'mail+ valueG+m.bangarra4uXgmail.com+DF
EDapp"ettingsF
Reading con%iguration %ile values %ro! a&&lications: to read configuration file values from applications
we are provided with a class ,onfigurationManager within the namespace "ystem.,onfiguration present
under the assembly "ystem.,onfiguration.dll. o consume the class we need to first add reference of the
assembly using the J)dd 8eferenceK window and we find the assemblies under .=et ab, after adding the
reference of assembly import the namespace and read the values as following?
$on%iguration,anager.A&&Settings.;et-<94e:=. 7: string -returns t'e value %or given 4e
as string.
o test the above process add a configuration file in the pro4ect and store values in it as shown
above within the EconfigurationFDEconfigurationsF tags. =ow add a new form in the pro4ect place a button
on it setting the ext as J8ead ,onfiguration 5aluesK and write the following code in code view?
#sing S/ste*.Con0ig#rtion;
Under ,ead Con-iguration #alues Button:
string cn*e = Con0ig#rtionMnger.2$$Settings.Jet("Cn*e");
string ddr = Con0ig#rtionMnger.2$$Settings.Jet("2ddress");
string $'one = Con0ig#rtionMnger.2$$Settings.Jet("P'one");
21
string e*il = Con0ig#rtionMnger.2$$Settings.Jet("5*il");
Messge%o&.S'ow(cn*e B Kn- B ddr B Kn- B $'one B Kn- B e*il);
Storing $onnection Strings under con%iguration %iles:
9e can store the connection string values also in configuration files so that we don7t re3uire to
specify the connection strings in all forms and whenever we want to change it we can ma%e the change
directly under the configuration file. o store connection strings in the configuration file we are provided
with a tag Econnection"tringsF same as Eapp"ettingsF tag, so we can maintain the connection string
values in the configuration file under EconfigurationF tag as following?
Econnection"tringsF
Eadd nameG+(,on"tr+ connection"tringG+@ser 2dG"cott0PasswordGtiger0!ata "ourceGE"erver =ameF+
provider=ameG+Msdaora+DF
Eadd nameG+",on"tr+ connection"tring G+@ser 2dG"a0PasswordGEyour passwordF0
!atabaseGETour !1 =ameF0!ata "ourceGE"erver =ameF+ provider=ameG+"3l(ledb+DF
EDconnection"tringsF
Note: we can read the connection string values from our application as following and use them?
string oconstr = Con0ig#rtionMnger.ConnectionStrings+"OConStr",.ConnectionString;
string o$rovider = Con0ig#rtionMnger.ConnectionStrings+"OConStr",.Provider4*e;
string sconstr = Con0ig#rtionMnger.ConnectionStrings+"SConStr",.ConnectionString;
string s$rovider = Con0ig#rtionMnger.ConnectionStrings+"SConStr",.Provider4*e;
Data;ridVie(: this control is used for displaying the data in the form of a table i.e. rows and columns. o
display data in the control first we need to bind the !ataable of !ata"et to the Lrid5iew control by using
its !ata"ource property as following? data;ridVie(5.DataSource > 9datata"le:
!ataLrid5iew control has a specialty i.e. changes performed to data in it gets reflected directly to
the data of !ataable to which it was bound, so that we can update dataset bac% to database directly.
o test this process add a new >orm in the pro4ect and place a !ataLrid5iew control on it setting
its doc% property as top. =ow place 2 buttons on the form setting the text as "ave and ,lose and write the
code?
#sing S/ste*.Dt.S)lClient; #sing S/ste*.Con0ig#rtion;
Declarations: S)lConnection con; S)lDt2d$ter d; S)lCo**nd%#ilder cb; DtSet ds;
Under 'or" Load:
string constr = Con0ig#rtionMnger.ConnectionStrings+"SConStr",.ConnectionString;
con = new S)lConnection(constr); ds = new DtSet();
d = new S)lDt2d$ter("Select 5no, 5n*e, 6ob, Slr/ 7ro* 5*$lo/ee Order %/ 5no", con);
d.7ill(ds, "5*$lo/ee"); dtJrid1iew;.DtSo#rce = ds.(bles+3,;
Under Save Button:
cb G new "3l,ommand1uilder#da$0 da.@pdate#ds, +'mployee+$0 Message1ox."how#+!ata saved to !1
"erver.+$0
$onnecting (it' Oracle Data"ase using $lasses o% Sste!.Data.Oracle$lient Na!es&ace:
2f we want to connect with (racle !atabase using classes of (racle,lient namespace we need to
first add the reference of "ystem.!ata.(racle,lient.dll.
21
Note: 2n 5" 2616 we will not find that assembly by default in the add reference window so to get it into
add reference window first you need to change the Jarget >ramewor%K of our pro4ect to .=et >ramewor%
A, default will be .=et >ramewor% A ,lient Profile and in this we cannot consume all assemblies of .net,
after changing the target framewor% we can access all .net assemblies. o change target framewor% of
pro4ect open pro4ect properties window and under that we find a ,ombo1ox arget >ramewor% showing
different framewor%7s in which we can develop an application, select .=et >ramewor% A and select JTesK in
the confirmation window.
Loading !ulti&le ta"les into DataSet:
) !ata"et can hold any no. of tables in it0 if we want to load multiple tables into a !ataset we have 2
different approaches.
1. @sing a single !ata)dapter we can load any no. of tables into the !ata"et by changing the
"elect,ommand of adapter each time after calling >ill and loading a table into !ata"et. 2n this
approach if we want to ma%e any changes to the data of dataset and send it bac% to database we
can do it on last table of the dataset only because an adapter can hold all the A commands only
for a single table i.e. for the last "elect,ommand we have given only the re3uired insert, update
and delete commands will be generated by ,ommand1uilder class.
2. @sing a separate !ata)dapter for each table being loaded into !ata"et we can load multiple
tables. 2n this approach it will be possible to update all the tables data, bac% to the database
because each table is using an individual !ata)dapter that will hold the re3uired insert, update
and delete commands for a table and more over here each table can also be loaded from a
different data source i.e. 1 table from (racle 1 table from "3l "erver etc.
DataVie( ? &ust li%e we have 5iews in "/L, we have !ata5iew ob4ect in )!(.=et. ) !ata5iew ob4ect
represents a customiYed view of !ataable ob4ect. (perations li%e "orting0 "earching can be performed
on a !ata5iew ob4ect. 2n scenarios li%e retrieval of a subset of data from a !ataable, we can ma%e use
of !ata5iew to get this data. =ote that the !efault5iew property of a !ataable returns the default data
view for the !ataable.
)sing a DataVie( %or %iltering or sorting t'e data under DataTa"le ?
Ste&5? ,reate an ob4ect of class !ata5iew by calling !efault5iew property on the !ataable which will
return a !ata5iew ob4ect with same structure of the table on which the property is called.
E.g: !ata5iew dv G ds.ablesHJ'mpKI.!efault5iew0
Ste&6? "pecify a condition for filter by ma%ing use of the 8ow>ilter property or specify a column for
sorting the data using "ort property of !ata5iew class.
E.g: dv.8ow>ilter G J&ob G ZManager7K0 dv.8ow>ilter G J"al F 2:66K0
dv.8ow>ilter G J&ob G ZManager7 )nd "al F 2:66K0dv.8ow>ilter G J&ob G ZManager7 (r "al F
2:66K0
dv."ort G J"alK0 or dv."ort G J"al !escK0 dv."ort G J"al, ,ommK0 or dv."ort G J"al, ,omm !escK0
Loading !ulti&le ta"les into a DataSet using single DataAda&ter and %iltering t'e data using
DataVie(: )dd a new form in the pro4ect, place a ,ombo1ox control at top center, place a !ataLrid5iew
control below and write the following code after adding the reference of "ystem.!ata.(racle,lient.dll
assembly.
#sing S/ste*.Dt.OrcleClient; #sing S/ste*.Con0ig#rtion;
Declarations: OrcleConnection con; OrcleDt2d$ter d; DtSet ds; bool 0lg = 0lse;
Under 'or" LoadE string constr =
Con0ig#rtionMnger.ConnectionStrings+"OConStr",.ConnectionString;
con = new OrcleConnection(OConStr); ds = new DtSet();
d = new OrcleDt2d$ter(Select L 0ro* De$t-, con); d.7ill(ds, De$t-);
d.SelectCo**nd.Co**nd(e&t = Select L 7ro* 5*$-; d.7ill(ds, 5*$-);
co*bo%o&;.DtSo#rce = ds.(bles+De$t-,; co*bo%o&;.Dis$l/Me*ber = Dn*e-;
21
co*bo%o&;.1l#eMe*ber = De$tno-; co*bo%o&;.Selected"nde& = A;; co*bo%o&;.(e&t = Select
De$rt*ent-;
dtJrid1iew;.DtSo#rce = ds.(bles+5*$-,; 0lg = tr#e;
Under Co"boBo* SelectedInde*Changed:
i0(0lg) :
Dt1iew dv = ds.(bles+5*$-,.De0#lt1iew; dv.<ow7ilter = De$tno=- B co*bo%o&;.Selected1l#e;
dv.Sort = Sl- or dv.Sort = Sl Desc-; or dv.Sort = Sl, Co**-; or dv.Sort = Sl, Co** Desc-;
@
Note: &ust li%e we can bind a !ataable to !ataLrid5iew control in the same way it can also be bound to
,ombo1ox and List1ox controls using !ata"ource property but these controls even if bound with the
table they can display only a single column. "o using !isplayMember property of the controls we need to
specify which column has to be displayed. 9e can also bind another column of the table using
5alueMember property of the controls but that column values will not be visible to end user where as we
can access them in code using "elected5alue property of control for the selected !isplayMember.
Loading !ulti&le ta"les into a DataSet %ro! di%%erent DataSources using !ulti&le DataAda&ters:
)dd a new form in the pro4ect, place a "plit,ontainer on it which comes with 2 panels in it. =ow
place a button on each panel and set the doc% property of button as top. "et the caption of the first button
as J"ave !ata to "3l "erverK and caption of second button as J"ave !ata to (racleK. hen add a
!ataLrid5iew control on each panel and set their doc% property as >ill. hen write the following code?
#sing S/ste*.Dt.S)lClient; #sing S/ste*.Dt.OrcleClient; #sing S/ste*.Con0ig#rtion;
Declarations:
S)lConnection scon; S)lDt2d$ter sd; S)lCo**nd%#ilder scb;
OrcleConnection ocon; OrcleDt2d$ter od; OrcleCo**nd%#ilder ocb; DtSet ds;
Under 'or" Load:
string sconstr = Con0ig#rtionMnger.ConnectionStrings+"SConStr",.ConnectionString;
string oconstr = Con0ig#rtionMnger.ConnectionStrings+"OConStr",.ConnectionString;
scon=new S)lConnection(sconstr); sd=new S)lDt2d$ter("Select 5no,5n*e,6ob,Slr/ 7ro*
5*$lo/ee", scon);
ocon = new OrcleConnection(oconstr); od = new OrcleDt2d$ter("Select L 7ro* Slgrde", ocon);
ds = new DtSet(); sd.7ill(ds, "5*$lo/ee"); od.7ill(ds, "Slgrde");
dtJrid1iew;.DtSo#rce = ds.(bles+"5*$lo/ee",;dtJrid1iew=.DtSo#rce =
ds.(bles+"Slgrde",;
Under Save Data to Sql Server Button:
scb=new S)lCo**nd%#ilder(sd);sd.!$dte(ds, "5*$lo/ee");Messge%o&.S'ow("Dt sved to S)l
Server D%.");
Under Save Data to Oracle Button:
ocb=new OrcleCo**nd%#ilder(od);od.!$dte(ds, "Slgrde");Messge%o&.S'ow("Dt sved to
Orcle D%.");
DataRelation:
!ata8elation is used to relate two !ataable ob4ects to each other through !ata,olumn ob4ects. >or
example, in a !eptD'mp relationship, the !ept table is the parent and the 'mp table is the child of the
relationship. his is similar to a primary %eyDforeign %ey relationship. 8elationships are created between
matching columns in the parent and child tables. hat is, the !ataype value for both columns must be
identical.
o use foreign %ey constraint we need a parent table that contains master data and a child table that
contains detailed data corresponding to master data. Parent table should contain a 8eference Pey
,olumn with a Primary Pey or @ni3ue Pey ,onstraints imposed on it, and child table should contain a
21
>oreign Pey ,olumn with >oreign Pey ,onstraint imposed on it which refers into the values of 8eference
Pey ,olumn. 2f relationships are established between tables following rules comes into picture?
1. ,annot store a value in the foreign %ey column of child table, provided the given value is not
present in reference %ey column of parent table.
2. ,annot delete a row from parent table provided the given reference %ey value of the record being
deleted has child records in the child table without addressing what to do with the corresponding
child records.
B. ,annot update reference %ey value of the parent table provided the given reference %ey value
being updated has child records in the child table without addressing what to do with the
corresponding child records.
2f we want to establish same type of relations between tables of a !ata"et also, we can do it with
the help of !ata8elation class. DataRelation -string na!e, Data$olu!n R?col, Data$olu!n 2?col.
)fter creating ob4ect of !ata8elation it has to be added explictly to the !ata"et under which
tables were present using 8elations.)dd method of !ata"et.
9dataset:.Relations.Add-DataRelation dr.
>or deleting or updating reference %ey values in parent table if the reference %ey value has an
child records in the child table some rules comes into picture for delete and update %nown as !elete8ules
and @pdate8ules, those are?
5. None: ,annot delete or update reference %ey value of parent table when corresponding child records
exists in child table, this rule is applied by default under !1;s.
6. $ascade: 2n this case we can delete or update reference %ey values of parent table, but the
corresponding child records in child table will also be deleted or updated, this rule is applied by default in
case of !ata"et;s.
@. Set Null: 2n this case also we can delete or update reference %ey values of parent table but the
corresponding child records foreign %ey value changes to null.
A. Set De%ault: his is same as "et =ull, but in this case the corresponding child records foreign %ey
value changes to default value of the column.
Note: we need to apply re3uired rule for delete or update on !ata8elation using following statements?
9datarelation:.$'ild?e$onstraint.DeleteRule > Rule.9rule:A
9datarelation:.$'ild?e$onstraint.)&dateRule > Rule.9rule:A
o use "et!efault rule first we need to set a default value for foreign column using the following
statement? Edatata"le:.$olu!nsBna!eC.De%aultValue>9value:
Loading !ulti&le ta"les into a DataSet and esta"lis'ing relation "et(een t'e ta"les:
)dd a new form in the pro4ect, place a "plit,ontainer on it and change the (rientation property of
the control as .oriYontal so that the panels under the "plit,ontainer will be horiYontally aligned #default is
vertical$. Place a !ataLrid5iew control on each panel and set their !oc% property as >ill. =ow write the
following code?
#sing S/ste*.Dt.OrcleClient; #sing S/ste*.Con0ig#rtion;
Declarations: OrcleConnection con; OrcleDt2d$ter d;, d=; DtSet ds; Dt<eltion dr;
Under 'or" Load: string constr =
Con0ig#rtionMnger.ConnectionStrings+OSConStr",.ConnectionString;
con = new OrcleConnection(constr); ds = new DtSet();
d; = new OrcleDt2d$ter(Select L 7ro* De$t-, con); d;.7ill(ds, "De$t");
d= = new OrcleDt2d$ter(Select L 7ro* 5*$-, con); d=.7ill(ds, "5*$");
21
dr = new Dt<eltion("5*$De$t", ds.(bles+De$t-,.Col#*ns+"De$tno",,
ds.(bles+5*$-,.Col#*ns+"De$tno",);
ds.<eltions.2dd(dr);
dr.C'ild9e/Constrint.Delete<#le = <#le.4one; dr.C'ild9e/Constrint.!$dte<#le = <#le.4one;
dtJrid1iew;.DtSo#rce = ds.(bles+"De$t",; dtJrid1iew=.DtSo#rce = ds.(bles+"5*$",;
Note: @se the following statement if re3uired for setting a default value to foreign %ey column?
ds.(bles+"5*$",.Col#*ns+"De$tno",.De0#lt1l#e = ?3;
Esta"lis'ing relations "et(een ta"les o% DataSet and dis&laing data in ParentD$'ild vie(:
2t is possible to establish relations between tables of a !ata"et and display the data in
ParentD,hild view with the help of a class %nown as 1inding"ource to test this add a new form in the
pro4ect, place a "plit,ontainer on it and change the (rientation property as .oriYontal. Place a
!ataLrid5iew control on each panel and set their !oc% property as >ill. =ow write the following code?
#sing S/ste*.Dt.OrcleClient; #sing S/ste*.Con0ig#rtion;
Declarations: OrcleConnection con; OrcleDt2d$ter d;, d=; DtSet ds;
Under 'or" Load: string constr =
Con0ig#rtionMnger.ConnectionStrings+"OConStr",.ConnectionString;
con = new OrcleConnection(constr);
d;=new OrcleDt2d$ter("Select L 7ro* De$t", con); d==new OrcleDt2d$ter("Select L 7ro*
5*$", con);
ds = new DtSet(); d;.7ill(ds, "De$t"); d=.7ill(ds, "5*$");
ds.<eltions.2dd("MsterDetil",ds.(bles+3,.Col#*ns+"De$tno",,ds.(bles+;,.Col#*ns+"De$tno",);
%indingSo#rce bsDe$t = new %indingSo#rce(); bsDe$t.DtSo#rce = ds; bsDe$t.DtMe*ber = "De$t";
%indingSo#rce bs5*$ = new %indingSo#rce(); bs5*$.DtSo#rce = bsDe$t; bs5*$.DtMe*ber =
"MsterDetil";
dtJrid1iew;.DtSo#rce = bsDe$t; dtJrid1iew=.DtSo#rce = bs5*$;
,a/or Di%%erences "et(een DataSet and DataReader:
!ata"et is disconnected architecture while !ata8eader has live connection while reading data.
2f we want to cache data and pass to a different tier !ata"et7s will be the best choice.
2f we want to move bac% while reading records, !ata8eader does not support this functionality.
(ne of the biggest drawbac%s of !ata"et is speed as !ata"et carry considerable overhead
because of relations0 multiple tables7 etc speed is slower than !ata8eader, so always try to use
!ata8eader where ever possible as it7s meant especially for speed performance.
$o!!unication (it' Data Sources using ODB$ Drivers
2n the case of (ledb, "3l,lient and (racle,lient classes we use providers for !ata "ource
communication where as in case of (dbc classes we use drivers for !ata "ource communication.
Providers will be on server side so within the connection string if we specify the provider name along with
other details li%e server name, user id, password we can communication with data sources, whereas
drivers will be sitting on client machines so to use them first we need to configure the appropriate driver
with data source and then from our application using (dbc classes we should communicate with drivers
which will in turn communicate with the data sources.
(dbc offers different drivers for connecting with different data sources which comes along with
(", to use them first we need to configure an appropriate driver to its specific data source by supplying all
the re3uired connection details and they are stored internally with a name %nown as !"= #!ata "ource
=ame$, this should be specified by us only while configuring with the driver. )fter configuring the !"=, we
can use that !"= in our .net app so that (dbc ,lasses can tal% with the !ata "ource ma%ing use of the
driver that has been configured as following?
21
OdbcConnection con . new OdbcConnection(/Dsn.0na"e o- the dsn we have created1/2
$on%iguring a DSN: to configure !"= go to ,ontrol Panel -F )dministrative ools -F !ata "ources
#(!1,$, clic% on it to open ;(!1, !ata "ource )dministrator; window. 2n the window opened clic% on
)dd button -F choose a driver for (racle or "3l "erver or M" 'xcel etc., and clic% >inish, which opens a
window in that first enter a name for !"= and then supply connection details li%e @ser 2d, Password,
!atabase, "erver etc., and ,lic% finish, which adds !"= in !ata "ource )dministrator window.
$on%iguring a DSN (it' S#l Server and Oracle Data"ases:
(pen (!1, !ata "ource )dministrator window, clic% on )dd button, select a driver for "3l
"erver and clic% >inish button, which opens a window, in it enter the following details, =ame? "3l!sn,
!escription? ,onnects with "3l "erver !atabase, "erver? E"erver =ameF, clic% on =ext button, select the
8adio1utton J@sing "3l "erver )uthenticationK, enter the Login 2!? E@ser =ameF, Password? EPwdF,
clic% on =ext button, select the ,hec%1ox J,hange the default database toK, and select the !atabase to
which we want to configure with below, clic% on =ext button and ,lic% on >inish button which displays a
window showing the connection details, clic% on (% button which adds the !"= under (!1, !ata
"ource )dministrator window.
)gain clic% on )dd button, select a driver for (racle and clic% >inish button, which opens a
window, in it enter the following details, !ata "ource =ame? (ra!sn, !escription? ,onnects with (racle
!atabase, =" "ervice =ame? E"erver =ameF, @ser 2!? "cottDtiger, clic% on (% button which adds the
!"= under (!1, !ata "ource )dministrator window.
=ow add a new form in the Pro4ect place 2 buttons on it and set their caption as J,onnect with
(racle using (!1, !riverK and J,onnect with "3l "erver using (!1, !riverK. Lo to code view and write
the following code?
#sing S/ste*.Dt.Odbc;
Declarations: OdbcConnection ocon, scon;
Under Connect with Oracle using ODBC Driver: ocon = new OdbcConnection(Dsn=OrDsn-);
ocon.O$en(); Messge%o&.S'ow(ocon.Stte.(oString()); ocon.Close();
Messge%o&.S'ow(ocon.Stte.(oString());
Under Connect with Sql Server using ODBC Driver: scon = new OdbcConnection(Dsn=S)lDsn-);
scon.O$en(); Messge%o&.S'ow(scon.Stte.(oString()); scon.Close();
Messge%o&.S'ow(scon.Stte.(oString());
Accessing ,S E0cel data %ro! .Net A&&lication
M" 'xcel is a file system which stores data in the form of rows and columns same as a database
table. )n 'xcel document is referred as 9or% 1oo% that contains 9or% "heets in it, wor% boo%s are
considered as databases and wor% sheets are considered as tables. >irst row of wor% sheet can store
column names.
$reating an E0cel docu!ent:
Lo to "tart Menu -F Programs -F Microsoft (ffice -F Microsoft (ffice 'xcel, clic% on it to open, by
default the document contains B wor% sheets in it. =ow in the first row of the sheet1 enter column names
for "tudent table as "no, "name, ,lass, >ees and from the second row enter few records in it. =ow in
bottom of the document change the sheet name "heet1 as "tudent and select Z"ave )s7 choose Z'xcel
*W [ 266B 9or%boo%7, name the document as "chool.xls in your desired location.
$onnecting (it' E0cel docu!ent %ro! .Net A&&lication?
9e can connect with 'xcel documents from .=et application by using !rivers or Providers also.
o connect with drivers first we need to configure (!1, driver for 'xcel. o configure driver go to "tart
Menu -F ,ontrol Panel -F )dministrative ools -F !ata "ources #(!1,$, clic% on it to open (!1, !ata
"ource )dministrator window, ,lic% )dd button, select Microsoft 'xcel #U.xls$ driver, ,lic% finish and 'nter
the following details, !ata "ource =ame? 'xcel!sn, !escription? ,onnects with 'xcel document, and clic%
on "elect 9or%boo% button to choose the "chool.xls document from it physical location and clic% on the
21
(% button which adds the !"= under (!1, !ata "ource )dministrator window. =ow add a new
windows form in the pro4ect and design it as following?
#sing S/ste*.Dt.OD%C;
Declarations: OD%CConnection con; OD%CCo**nd c*d; OD%CDt<eder dr; string S)lStr;
Under 'or" LoadE
con = new OD%CConnection("Dsn=5&celDsn;<edOnl/=3");
c*d = new OD%CCo**nd(); c*d.Connection = con; con.O$en(); CodDt();
lbel;.(e&t=dr.Jet4*e(3); lbel=.(e&t=dr.Jet4*e(;); lbel>.(e&t=dr.Jet4*e(=);
lbel?.(e&t=dr.Jet4*e(>);
$rivte void LoadData( :
c*d.Co**nd(e&t = "Select L 7ro* +St#dentM,"; dr = c*d.5&ec#te<eder(); S'owDt();
@
$rivte void ShowData() :
i0 (dr.<ed()) :
te&t%o&;.(e&t = dr+3,.(oString(); te&t%o&=.(e&t = dr+;,.(oString();
te&t%o&>.(e&t = dr+=,.(oString(); te&t%o&?.(e&t = dr+>,.(oString();
@
else
Messge%o&.S'ow("4o dt e&ists.-);
@
Under )e*t Button: S'owDt();
Under Clear Button: te&t%o&;.(e&t=te&t%o&=.(e&t=te&t%o&>.(e&t=te&t%o&?.(e&t = ""; te&t%o&;.7oc#s();
$rivte void E*ecuteD&L( :
dr.Close(); c*d.Co**nd(e&t = S)lStr;
i0 (c*d.5&ec#te4onN#er/() > 3) Messge%o&.S'ow(""nsert Or !$dte o$ertion ws
s#ccess0#l.");
else Messge%o&.S'ow(""nsert or !$dte o$ertion 0iled.");
CodDt();
@
)nder *nsert Button: s3lstr G "tring.>ormat#J2nsert 2nto H"tudent\I 5alues #M6N, ZM1N7 M2N, MBN$K,
text1ox1.ext, text1ox2.ext, text1oxB.ext, text1oxA.ext$0 dr.,lose#$0 'xecute!ML#$0
)nder )&date Button: s3lstr G "tring.>ormat#J@pdate H"tudent\I "et "nameG;M6N7, ,lassGM1N, >eesGM2N
where "noGMBNK, text1ox2.ext, text1oxB.ext, text1oxA.ext, text1ox1.ext$0 'xecute!ML#$0
)nder $lose Button: this.,lose#$0
$onnecting (it' E0cel using OLEDB Provider:
o connect with 'xcel documents using (L'!1 Provider, ,onnection "tring is should be as following?
EProvider>,icroso%t.Fet.Oled".G.HA Data Source>9&at' o% e0cel %ile:A E0tended Pro&erties>E0cel
I.HE
Note: (dbc,onnection class opens connection with 'xcel !ocument in read only mode so if we want to
perform any manipulations to data in the document we need to open it in readDwrite mode by setting the
21
attribute JreadonlyG6K under the connection string, whereas (ledb,onnection will open the document in
readDwrite mode only so no need of using readonly attribute there.
Stored Procedures
9henever we want to interact with a database from an application we use s3l stmts. 9hen we
use s3l statements within the application we have a problem i.e. when the application runs s3l "tatements
will be sent to db for execution where the stmts will be parsed #compile$ and then executed. he process
of parsing ta%es place each time we run the application, because of this performance of our application
decreases. o overcome the above drawbac% write s3l statements directly under db only, with in an
ob4ect %nown as "tored Procedure and call them for execution. )s a "P is a pre-compiled bloc% of code
that is ready for execution will directly execute the statements without parsing each time.
Snta0 to de%ine a Stored Procedure:
$reate Procedure 9Na!e: B -9&ara!eter de%initions. C
As
Begin
9St!ts:
End
"P7s is similar to a method in our language.
(ublic void +est( 33ðod
Create Procedure +est( 33Stored Procedure
2f re3uired we can also define parameters but only optional. 2f we want to pass parameters to a
"3l "erver "P prefix the special character JXK before parameter name.
(ublic void +est(int * 33CShar(
Create Procedure +est(* nu"ber 33Oracle
Create Procedure +est(4* int 33Sql Server
) "P can also return values, to return a value we use out clause in (racle and (utput clause in
"3l "erver.
(ublic void +est(int *! re- int % 33CShar(
Create Procedure +est(* nu"ber! % out nu"ber 33Oracle
Create Procedure +est(4* int! 4% int out(ut 33Sql Server
$reating a Stored Procedure:
9e can create a "P in "3l "erver either by using "3l "erver Management "tudio or 5isual "tudio.=et
also. o create a "P from 5isual "tudio first we need to configure our !atabase under "erver 'xplorer, to
do this go to view menu, select "erver 'xplorer which gets launched on L." of the studio. o configure it
right clic% on the node J!ata ,onnectionsK, select J)dd ,onnectionK which opens a window as%ing to
choose a !ata "ource select M" "3l "erver, clic% o%, which opens J)dd ,onnectionK window and under it
provide the following details?
1. "erver =ame? E=ame of the "erverF
2. )uthentication? 9indows or "3l "erver #provide @ser =ame and Password$
21
B. !atabase? E!1 =ameF
,lic% on the (P button which adds the !1 under "erver 'xplorer, expand it, and right clic% on the
node "tored Procedures, select J)dd =ew "tored ProcedureK which opens a window and write the
following?
Create Procedure E"(lo%ee5Select
6s
Select Eno! Ena"e! $ob! Salara%! 'ro" E"(lo%ee
-=ow right clic% on the document window and select execute which will create the procedure on !atabase
"erver.
$alling a SP %ro! .Net a&&lication: if we want to call a "P from .net application we use !ata)dapter
class if it is a "elect "P to load data into a !ata"et or else we can use ,ommand class if the "P is of any
operation but here if it is "elect "P we can load data either into a !ata8eader or !ata"et also. o call the
"P we adopt the below process?
Ste& 5: ,reate an ob4ect of class ,ommand or !ata)dapter by passing "P name as argument to their
constructor.
Dt2d$ter d = new Dt2d$ter(5*$lo/ee.Select-, con);
or
Co**nd c*d = new Co**nd (5*$lo/ee.Select-, con);
Ste& 6: ,hange the ,ommandype property of "elect,ommand of !ata)dapter ob4ect or
,ommandype property of ,ommand ob4ect as "toredProcedure because by default ,ommandype
property is configured to execute "3l "tatements only after changing the property we can call "tored
Procedures.
d.SelectCo**nd.Co**nd(/$e = Co**nd(/$e.StoredProced#re;
or
c*d.Co**nd(/$e = Co**nd(/$e.StoredProced#re;
Ste& @: 2f the "P has any parameters we need to pass values to those parameters by adding the
parameters with their corresponding values under "elect,ommand of !ata)dapter or ,ommand.
Ste& G: o call the "elect "P using !ata)dapter we can directly call >ill method on !ata)dapter ob4ect
and load data into !ata"et. 2f we want to call "elect "P using ,ommand call the 'xecute8eader#$
method on ,ommand ob4ect so that data gets loaded into a !ata8eader or else if we want to load the
data into a !ata"et create ob4ect of !ata)dapter by passing this command ob4ect as a parameter and
then call >ill method on !ata)dapter. 2f the "P contains any non-3uery operations li%e 2nsert or @pdate or
!elete then call 'xecute=on/uery method on command to execute the "P.
$alling a"ove Stored Procedure using DataAda&ter: 2n a new form place a !ataLrid5iew and write
below code?
#sing S/ste*.Con0ig#rtion; #sing S/ste*.Dt.S)lClient;
Declarations: S)lConnection con; S)lDt2d$ter d; DtSet ds;
Under 'or" Load: string constr =
Con0ig#rtionMnger.ConnectionStrings+"SConStr",.ConnectionString;
con = new S)lConnection(constr); d = new S)lDt2d$ter(5*$lo/ee.Select-, con);
d.SelectCo**nd.Co**nd(/$e = Co**nd(/$e.StoredProced#re;
ds = new DtSet(); d.7ill(ds, 5*$lo/ee-); dtJrid1iew;.DtSo#rce = ds.(bles+3,;
$alling t'e a"ove Stored Procedure using $o!!and: ta%e a new form and design it as following.
21
#sing S/ste*.Con0ig#rtion; #sing S/ste*.Dt.S)lClient;
Declarations: S)lConnection con; S)lCo**nd c*d; S)lDt<eder dr;
Under 'or" Load: string constr =
Con0ig#rtionMnger.ConnectionStrings+"SConStr",.ConnectionString;
con = new S)lConnection(constr); c*d = new S)lCo**nd("5*$lo/ee.Select", con);
c*d.Co**nd(/$e = Co**nd(/$e.StoredProced#re; con.O$en(); dr = c*d.5&ec#te<eder();
S'owDt();
lbel;.(e&t = dr.Jet4*e(3); lbel=.(e&t = dr.Jet4*e(;);
lbel>.(e&t = dr.Jet4*e(=); lbel?.(e&t = dr.Jet4*e(>);
$rivte void ShowData( :
i0 (dr.<ed()) :
te&t%o&;.(e&t = dr+3,.(oString(); te&t%o&=.(e&t = dr+;,.(oString();
te&t%o&>.(e&t = dr+=,.(oString(); te&t%o&?.(e&t = dr+>,.(oString();
@
else
Messge%o&.S'ow("Cst record o0 t'e tble");
@
Under )e*t Button: S'owDt();
Para!eters to Stored Procedures?
"P can be defined with parameters either to send values for execution or receiving values after
execution. 9hile calling a "P with parameters from .net application for each parameter of the "P we need
to add a matching parameter either under ,ommand or !ata)dapter i.e. for input parameter matching
input parameter has to be added and for output parameter a matching output parameter has to be added.
'very parameter that is added to ,ommand or !ata)dapter has : attributes to it li%e =ame, 5alue,
!bype, "iYe and !irection which can be 2nput#d$ or (utput or 2nput(utput #in case of oracle only$.
=ame refers to name of the parameter that is defined in "P.
5alue refers to value being assigned in case of input or value we are expecting in case of output.
!bype refers to data type of the parameter in terms of the !1 where the "P exists.
"iYe refers to siYe of data.
!irection specifies whether parameter is 2nput or (utput or 2nput(utput.
2f a "P has 2nput or (utput parameters we need to specify the following attributes while adding
parameters to ,ommand or !ata)dapter?
*n&ut Out&ut *n&utOut&ut
=ame Tes Tes Tes
5alue Tes =o Tes
!bype =o Tes Tes
21
"iYe =o 7es 7es H(nly in case of variable length
typesI
!irection =o Tes Tes
Adding *n&ut Para!eter under .Net A&&lication:
d.SelectCo**nd.Pr*eters.2dd8it'1l#e(string <$n*e>, obFect <$vl#e>);
or
c*d.Pr*eters.2dd8it'1l#e(string <$n*e>, obFect <$vl#e>);
Adding Out&ut Para!eter under .Net A&&lication:
d.SelectCo**nd.Pr*eters.2dd(string <$n*e>, <dbt/$e>).Direction = Pr*eterDirection.O#t$#t;
or
c*d.Pr*eters.2dd(string <$n*e>, <dbt/$e>).Direction = Pr*eterDirection.O#t$#t;
Adding Out&ut &ara!eter (it' siJe i% it is a varia"le lengt' t&e:
da."elect,ommand.Parameters.)dd#string EpnameF, EdbtypeF, int EsiYeF$.!irection G
Parameter!irection.(utput0
or
cmd.Parameters.)dd#string EpnameF, EdbtypeF, int EsiYeF$.!irection G Parameter!irection.(utput0
A%ter e0ecuting t'e SP (e can ca&ture Out&ut &ara!eter values as %ollo(ing:
ObFect obF = d.SelectCo**nd.Pr*eters+<$n*e>,.1l#e;
or
ObFect obF = c*d.Pr*eters+<$n*e>,.1l#e;
Per%or!ing Select and D,L O&erations using Stored Procedures:
o perform select, insert, update and delete operations using "P7s first define the following
procedures in !atabase.
2lter P<OC5D!<5 5*$lo/ee.Select (O5no "nt=4#ll, OStt#s bit=4#ll)
2s
%egin
"0 O5no "s 4#ll 2nd OStt#s "s 4#ll
Select 5no, 5n*e, 6ob, Slr/, Stt#s 7ro* 5*$lo/ee
5lse "0 O5no "s 4#ll
Select 5no, 5n*e, 6ob, Slr/, Stt#s 7ro* 5*$lo/ee 8'ere Stt#s=OStt#s
5lse
Select 5no, 5n*e, 6ob, Slr/, P'oto 7ro* 5*$lo/ee 8'ere 5no=O5no 2nd Stt#s=OStt#s
5nd
Crete Proced#re E"(lo%ee5Insert(O5n*e 1rc'r(H3), O6ob 1rc'r(H3), OSlr/ Mone/,
OP'oto "*ge, O5no "nt O#t$#t)
2s
%egin
Select O5no = "s4#ll(M&(5no), ;333) B ; 7ro* 5*$lo/ee
"nsert "nto 5*$lo/ee (5no, 5n*e, 6ob, Slr/, P'oto) 1l#es (O5no, O5n*e, O6ob, OSlr/,
OP'oto)
5nd
Crete Proced#re E"(lo%ee5U(date(O5no "nt, O5n*e 1rc'r(H3), O6ob 1rc'r(H3), OSlr/
Mone/, OP'oto "*ge)
2s
!$dte 5*$lo/ee Set 5n*e=O5n*e, 6ob=O6ob, Slr/=OSlr/, P'oto=OP'oto 8'ere
5no=O5no
C<52(5 P<OC5D!<5 E"(lo%ee5Delete (O5no "nt)
2s
21
!$dte 5*$lo/ee Set Stt#s=3 8'ere 5no=O5no
a%e a new form, design it as following by adding an (pen>ile!ialog control and then write below code?
#sing S/ste*.Con0ig#rtion; #sing S/ste*."O; #sing S/ste*.Dt.S)lClient; #sing Microso0t.1is#l%sic;
Declarations: S)lConnection con; S)lCo**nd c*d; S)lDt2d$ter d; DtSet ds;
string i*gPt'=--; b/te+, dt = n#ll;
)nder 2or! Load: string constr =
Con0ig#rtionMnger.ConnectionStrings+"SConStr",.ConnectionString;
con = new S)lConnection("ConStr"); c*d = new S)lCo**nd();
c*d.Connection = con; c*d.Co**nd(/$e = Co**nd(/$e.StoredProced#re;
Under Select Button: int 5no = int.Prse("nterction."n$#t%o&("5nter n 5*$lo/ee 4o."));
c*d.Pr*eters.Cler(); c*d.Co**nd(e&t = "5*$lo/ee.Select"; ds = new DtSet();
c*d.Pr*eters.2dd8it'1l#e("O5no", 5no); c*d.Pr*eters.2dd8it'1l#e("OStt#s", tr#e);
d = new S)lDt2d$ter(c*d); d.7ill(ds, "5*$lo/ee");
i0 (ds.(bles+3,.<ows.Co#nt > 3) :
te&t%o&;.(e&t = ds.(bles+3,.<ows+3,+3,.(oString(); te&t%o&=.(e&t = ds.(bles+3,.<ows+3,+;,.(oString();
te&t%o&>.(e&t = ds.(bles+3,.<ows+3,+=,.(oString(); te&t%o&?.(e&t = ds.(bles+3,.<ows+3,+>,.(oString();
i0 (ds.(bles+3,.<ows+3,+?, I= S/ste*.D%4#ll.1l#e) :
dt = (b/te+,)ds.(bles+3,.<ows+3,+?,;
Me*or/Stre* *s = new Me*or/Stre*(dt);
$ict#re%o&;."*ge = "*ge.7ro*Stre*(*s);
@
else : $ict#re%o&;."*ge = n#ll; @
@
else
Messge%o&.S'ow("5*$lo/ee doesnPt e&ist, $lese c'ecG t'e given e*$lo/ee n#*ber.", "8rning",
Messge%o&%#ttons.O9, Messge%o&"con.8rning);
Under Clear Button:
te&t%o&;.(e&t = te&t%o&=.(e&t = te&t%o&>.(e&t = te&t%o&?.(e&t = "";
$ict#re%o&;."*ge = n#ll; dt = n#ll; i*gPt' = ""; te&t%o&=.7oc#s();
Under Insert Button:
tr/ :
c*d.Pr*eters.Cler(); c*d.Co**nd(e&t = "5*$lo/ee."nsert";
c*d.Pr*eters.2dd8it'1l#e("O5n*e", te&t%o&=.(e&t);
c*d.Pr*eters.2dd8it'1l#e("O6ob", te&t%o&>.(e&t);
c*d.Pr*eters.2dd8it'1l#e("OSlr/", te&t%o&?.(e&t);
i0(i*gPt'.(ri*().Cengt' > 3) :
21
dt = 7ile.<ed2ll%/tes(i*gPt'); c*d.Pr*eters.2dd8it'1l#e("OP'oto", dt);
@
else :
c*d.Pr*eters.2dd8it'1l#e("OP'oto", D%4#ll.1l#e);
c*d.Pr*eters+"OP'oto",.S)lDb(/$e = S)lDb(/$e."*ge;
@
c*d.Pr*eters.2dd("O5no", S)lDb(/$e."nt).Direction = Pr*eterDirection.O#t$#t;
con.O$en(); c*d.5&ec#te4onN#er/();
te&t%o&;.(e&t = c*d.Pr*eters+"O5no",.1l#e.(oString();
@
ctc' (5&ce$tion e&)
: Messge%o&.S'ow(e&.Messge, "5rror Messge", Messge%o&%#ttons.O9,
Messge%o&"con.5rror); @
0inll/ : con.Close(); i*gPt' = -; dt = n#ll; @
Under U(date Button:
tr/ :
c*d.Pr*eters.Cler(); c*d.Co**nd(e&t = "5*$lo/ee.!$dte";
c*d.Pr*eters.2dd8it'1l#e("O5no", te&t%o&;.(e&t);
c*d.Pr*eters.2dd8it'1l#e("O5n*e", te&t%o&=.(e&t);
c*d.Pr*eters.2dd8it'1l#e("O6ob", te&t%o&>.(e&t);
c*d.Pr*eters.2dd8it'1l#e("OSlr/", te&t%o&?.(e&t);
i0 (i*gPt'.(ri*().Cengt' == 3 QQ dt == n#ll) :
c*d.Pr*eters.2dd8it'1l#e("OP'oto", D%4#ll.1l#e);
c*d.Pr*eters+"OP'oto",.S)lDb(/$e = S)lDb(/$e."*ge;
@
else i0 (i*gPt'.(ri*().Cengt' > 3) :
dt = 7ile.<ed2ll%/tes(i*gPt');
c*d.Pr*eters.2dd8it'1l#e("OP'oto", dt);
@
else i0 (dt I= n#ll) :
c*d.Pr*eters.2dd8it'1l#e("OP'oto", dt);
@
con.O$en(); c*d.5&ec#te4onN#er/();
Messge%o&.S'ow("<ecord #$dted #nder t'e dtbse tble.", ""n0or*tion Messge",
Messge%o&%#ttons.O9,
Messge%o&"con."n0or*tion);
@
ctc' (5&ce$tion e&)
: Messge%o&.S'ow(e&.Messge, "5rror Messge", Messge%o&%#ttons.O9, Messge%o&"con.5rror); @
0inll/ : con.Close(); i*gPt' = ""; dt = n#ll; @
Under Delete Button:
tr/ :
c*d.Pr*eters.Cler(); c*d.Co**nd(e&t = "5*$lo/ee.Delete";
c*d.Pr*eters.2dd8it'1l#e("O5no", te&t%o&;.(e&t);
con.O$en(); c*d.5&ec#te4onN#er/(); btnCler.Per0or*ClicG();
Messge%o&.S'ow("<ecord deleted #nder t'e dtbse tble.", "S)l Messge",
Messge%o&%#ttons.O9,
21
Messge%o&"con."n0or*tion);
@
ctc' (5&ce$tion e&)
: Messge%o&.S'ow(e&.Messge, "5rror Messge", Messge%o&%#ttons.O9, Messge%o&"con.5rror); @
0inll/ : con.Close(); @
)ote: w'en we cll Per0or*ClicG() *et'od on b#tton internll/ t'e ClicG o0 t't b#tton occ#rs.
Under Load I"age Button:
o$en7ileDilog;.7ilter = "6$eg "*ges (L.F$g)RL.F$gR%it*$ "*ges (L.b*$)RL.b*$R2ll 7iles (L.L)RL.L";
Dilog<es#lt dr = o$en7ileDilog;.S'owDilog();
i0 (dr == Dilog<es#lt.O9) :
i*gPt' = o$en7ileDilog;.7ile4*e; $ict#re%o&;."*geCoction = i*gPt';
@
,reate a new form as below for accessing all, active and in-active records from the table using select "P.
#sing S/ste*.Con0ig#rtion; #sing S/ste*.Dt.S)lClient;
Declarations: S)lConnection con; S)lDt2d$ter d; DtSet ds;
Under Select Button: string constr =
Con0ig#rtionMnger.ConnectionStrings+"SConStr",.ConnectionString;
con = new S)lConnection(constr); d = new S)lDt2d$ter("5*$lo/ee.Select", con);
d.SelectCo**nd.Co**nd(/$e = Co**nd(/$e.StoredProced#re; co*bo%o&;.Selected"nde& = 3;
Under Co"boBo* SelectedInde*Changed: d.SelectCo**nd.Pr*eters.Cler();
i0 (co*bo%o&;.Selected"nde& == ;) : d.SelectCo**nd.Pr*eters.2dd8it'1l#e("OStt#s", tr#e); @
else i0(co*bo%o&;.Selected"nde& == =) : d.SelectCo**nd.Pr*eters.2dd8it'1l#e("OStt#s",
0lse); @
ds = new DtSet(); d.7ill(ds, "5*$lo/ee"); dtJrid1iew;.DtSo#rce = ds.(bles+3,;
$reating a SP (it' "ot' *n&ut and Out&ut &ara!eters:
,reate a "P under "3l "erver !1 which ta%es the 'mployee =o. and returns the "alary,
Provident >und, Professional ax and =et "alary of the 'mployee by performing the calculations. 2n this
case writing the logic under the "P provides an advantage of ma%ing the changes easier in the future if
re3uired.
C<52(5 P<OC5D!<5 E"(lo%ee58etSalDetails (O5no "nt, OSlr/ Mone/ O#t$#t, OP7 Mone/
O#t$#t, OP( Mone/ O#t$#t, O4etSl Mone/ O#t$#t)
2s
%egin
Select OSlr/ = Slr/ 7ro* 5*$lo/ee 8'ere 5no = O5no 2nd Stt#s = ;;
Set OP7 = OSlr/ L 3.;=; Set OP( = OSlr/ L 3.3H; Set O4etSl = OSlr/ A (OP7 B OP();
5nd
$alling t'e a"ove Stored Procedure? ,reate a new form as following ] set read-only of 2
nd
to :
th
textbox7s as true.
!ataLrid5iew
21
#sing S/ste*.Dt.S)lClient;
Declarations: S)lConnection con; S)lCo**nd c*d;
Under 'or" LoadE string constr =
Con0ig#rtionMnger.ConnectionStrings+"SConStr",.ConnectionString;
con = new S)lConnection(constr); c*d = new S)lCo**nd("5*$lo/ee.JetSlDetils",con);
c*d.Co**nd(/$e = Co**nd(/$e.StoredProced#re;
Under E*ecute ButtonE
tr/ :
c*d.Pr*eters.Cler(); c*d.Pr*eters.2dd8it'1l#e("O5no", te&t%o&;.(e&t);
c*d.Pr*eters.2dd("OSlr/", S)lDb(/$e.Mone/).Direction = Pr*eterDirection.O#t$#t;
c*d.Pr*eters.2dd("OP7", S)lDb(/$e.Mone/).Direction = Pr*eterDirection.O#t$#t;
c*d.Pr*eters.2dd("OP(", S)lDb(/$e.Mone/).Direction = Pr*eterDirection.O#t$#t;
c*d.Pr*eters.2dd("O4etSl", S)lDb(/$e.Mone/).Direction = Pr*eterDirection.O#t$#t;
con.O$en(); c*d.5&ec#te4onN#er/();
te&t%o&=.(e&t = c*d.Pr*eters+"OSlr/",.1l#e.(oString();
te&t%o&>.(e&t=c*d.Pr*eters+"OP7",.1l#e.(oString();
te&t%o&?.(e&t=c*d.Pr*eters+"OP(",.1l#e.(oString();
te&t%o&H.(e&t = c*d.Pr*eters+"O4etSl",.1l#e.(oString();
@
ctc' (5&ce$tion e&)
: Messge%o&.S'ow(e&.Messge, "5rror Messge", Messge%o&%#ttons.O9, Messge%o&"con.5rror); @
0inll/ : con.Close(); @
Under Close Button: t'is.Close();
$alling Select Stored Procedures %ro! Oracle:
9e can7t use select statements directly in (racle "P7s as we used in "3l "erver, so to define a
select "P in (racle for retrieving any data from the table#s$ first we need to load the data from table into a
cursor under "P and then that cursor should be returned as an output parameter bac% to the application.
o send cursor as an output parameter from a "P we need to use 8ef ,ursors, because 8ef
,ursor is a data type #user defined$, which can be used as a procedure parameter, so first we need to
define a 8ef ,ursor type and that should be used as an (utput parameter to the "P. 9e define 8ef
,ursor types in (racle !atabase as following?
T&e 9t&e na!e: is Re% $ursorA E.g.: T&e Dna$ur is Re% $ursorA
o define the "P with 8ef ,ursor (utput Parameter first we need to define the 8ef ,ursor under
an ob4ect %nown as Pac%age which is a group of Procedures, >unctions, 5ariables and "3l "tatements
created as a single unit, used for storing of related ob4ects. ) pac%age has two parts?
5. Pac4age S&eci%ication or S&ec or Pac4age Keader
21
6. Pac4age Bod
Pac%age "pecification acts as an interface to the pac%age which contains only declaration of
types, variables, constants, exceptions, cursors and sub-programs. Pac%age 1ody is used to provide
implementation for the sub-programs, 3ueries for the cursors declared in the pac%age specification.
=ow let us define a pac%age header with a 8ef ,ursor type definition and also 2 "P7s for
selecting data from !'P and 'MP tables using the 8ef ,ursor type as an (utput Parameter and then
implement the "P7s under the Pac%age 1ody.
Ste& 5: De%ining Pac4age S&eci%ication:
Crete or <e$lce PcGge M/PcGge
2s
(/$e D/nC#r is <e0 C#rsor;
Proced#re Select.5*$(ec#r o#t D/nC#r);
Proced#re Select.De$t(dc#r o#t D/nC#r);
5nd M/PcGge;
S
Ste& 6: De%ining t'e Pac4age Bod:
Crete or <e$lce PcGge %od/ M/PcGge
2s
Proced#re Select.5*$(ec#r o#t D/nC#r)
"s
%egin
O$en ec#r 7or Select L 7ro* 5*$;
5nd Select.5*$;
Proced#re Select.De$t(dc#r o#t D/nC#r)
"s
%egin
O$en dc#r 0or Select L 7ro* De$t;
5nd Select.De$t;
5nd M/PcGge;
S
Ste& @: Dis&laing t'e data " loading it into t'e a&&lication:
=ow ta%e a new windows form place a "plit,ontainer on it, set its (rientation property as
.oriYontal, place a !ataLrid5iew control on each panel by setting their !oc% property as fill and write the
following code?
#sing S/ste*.Dt.OrcleClient;
DeclarationsE OrcleConnection con; OrcleDt2d$ter d;, d=; DtSet ds;
Under 'or" Load: string constr =
Con0ig#rtionMnger.ConnectionStrings+"OConStr",.ConnectionString;
con = new OrcleConnection(constr); d; = new OrcleDt2d$ter("M/PcGge.Select.5*$", con);
d;.SelectCo**nd.Co**nd(/$e = Co**nd(/$e.StoredProced#re;
d;.SelectCo**nd.Pr*eters.2dd("ec#r", Orcle(/$e.C#rsor).Direction=Pr*eterDirection.O#t$#t;
d= = new OrcleDt2d$ter("M/PcGge.Select.De$t", con);
d=.SelectCo**nd.Co**nd(/$e = Co**nd(/$e.StoredProced#re;
d=.SelectCo**nd.Pr*eters.2dd("dc#r", Orcle(/$e.C#rsor).Direction=Pr*eterDirection.O#t$#t;
ds = new DtSet(); d;.7ill(ds, "5*$"); d=.7ill(ds, "De$t");
dtJrid1iew;.DtSo#rce = ds.(bles+"De$t",; dtJrid1iew=.DtSo#rce = ds.(bles+"5*$",;