Вы находитесь на странице: 1из 27

JDBC

1: What is the difference between Database and Database management system?


Ans: Database is a collection of interrelated data. Database management system is a
software which can be used to manage the data by storing it on to the data base and by
retrieving it from the data base. And DBMS is a collection of interrelated data and
some set of programs to access the data.
There are 3 types of Database Management Systems.
Relational DataBase Management Systems RDBMS!" #t is a software
system$ which can be used to represents data in the form of tables. RDBMS
will use S%&' as a %ueries language.
(b)ect (riented DataBase Management Systems((DBMS!" #t is a software
system$ which can be used to represent the data in the form of ob)ects. This
DBMS will use (%& as a %uery language.
(b)ect Relational DataBase Management Systems(RDBMS!" #t is a DBMS
which will represents some part of the data in the form of tables and some
other part of the data in the form of ob)ects. This management system will use
S%&3 as a %uery &anguage$ it is a combination of S%&' and (%&.
2: How a query could be executed when we send a query to Database?
*hen we send an S%& %uery from S%& prompt to the DataBase+ngine$ then
Database +ngine will ta,e the following steps.
%uery To,eni-ation" This phase will ta,e S%& .uery as an input and devide
into stream of to,ens.
%uery /arsing" This phase will ta,e stream of to,ens as an input$ with them it
tried to construct a .uery tree. #f .uery parser constructs .uery tree
successfully then it was an indication that no grammatical mista,es in the
ta,en S%& .uery. (therwise there are some syntactical errors in the ta,en S%&
.uery.
%uery (ptimi-ation" This phase will ta,e .uery tree as an input and performs
number of .uery optimi-ation mechanisms to reduce e0ecution time and
memory utili-ation.
%uery +0ecution" This phase will ta,e optimi-ed .uery as an input and
e0ecutes that S%& .uery by using interpreters internally as a result we will get
some output on the S%& prompt.
3: What is Drier? How !any Driers are aailable in JDBC? What are the ty"es?
#t is a process of interacting with the database from a )ava application.
#n 1DB2 applications we must specify the complete database logic in )ava
application as for the )ava A/# representations$ later on we need to send )ava
represented database logic to the database engineDB+!.
DB+ must e0ecute the database logic but it was configured as per the )ava
representations but DB+ able to understand only %uery &anguage
representations.
At the above situation if we want to e0ecute our database logic$ we need to use
one interface in between )ava application and the database$ that interface must
convert )ava representations to .uery language representations and .uery
language representations to )ava representations. 3ow this interface is called
as a 4Driver5.
Driver:
#t is a software or an interface e0isted in between a )ava application and
database$ which will map )ava api calls with .uery language api calls and vice
versa.
#nitially sun Microsystems has provided 4driver interface5 to the mar,et with
this sun Microsystems has given an intimation to all the database vendors to
have their own implementation as per their re.uirements for the Driver
interface.
As a response all the database vendors are providing their own implementation
for the Driver interface inorder to interact with the respective databases from a
)ava application.
The users of the respective databases they must get the respective database
provided Driver implementation from the database software and ma,e use as
part of the 1DB2 applications to interact with the respective databases form a
)ava application.
Types of Drivers:
There are 6789 number of Drivers in the mar,et. But all these Drivers could
be classified into the following : types.
Type 6 Driver
Type ' Driver
Type 3 Driver
Type : Driver
Type 1 Driver:
o Type 6 Driver is also called as 1dbc;(dbc Driver or Bridge Driver.
o 1dbc;(dbc Driver is an implementation to Driver interface provided by
the sun Microsystems along with the )ava software.
o 1dbc;(dbc Driver internally depends on the Microsoft product (dbc
Driver.
o (dbc is nothing but open database connectivity. #t is a open
specification which can be used to interact with any type of databases.
Advantages:
This Driver is already available with )ava software that<s why no need to
bother about how to get the Driver implementation e0plicitily.
Allmost all the databases could support this Driver.
Dis advantages:
This Driver internally depends on (dbc Driver that<s why it is not suitable for
internet or web applications or networ, applications.
This Driver is a slower Driver$ why because 1dbc;(dbc Driver will convert
)ava calls to (dbc calls. Then (dbc Driver has to convert (dbc calls to .uery
language calls.
This driver is not portable Driver why because it was not complete the )ava
implementations in 1dbc;(dbc Driver.
#t we want to use 1dbc;(dbc Driver in our )dbc applications then we must
re.uire to install (dbc;3ative &ibrary.
Type 2 Driver:
Type ' Driver is also called as 4part )ava part native Driver5. i.e.$ this Driver
was designed by using some part of the )ava implementations and some other part of
the database vendor provided native implementations. This Driver is also called as
4native driver5.
Advantages:
*hen compared to Type 6 driver it is efficient driver why because Type '
driver directly will convert )ava api calls to database vendor api calls.
Dis advantages:
#f we want to use Type ' Driver in our 1dbc applications then we must re.uire
to install database vendor native api.
#t is a costful Driver.
#t is not suitable for web applicadtions$ distributed applications and web
applications.
Type ' Driver performance is low when compared to Type 3 and Type :
drivers.
This driver is not portable driver. *hy because this driver was not designed
completely in )ava technology.
Type 3 Driver:
o #t is also called as middleware database access server driver.
o This driver could be used to interact with multiple databases from the
multiple clients.
o This driver could be used in collaboration with application server.
o This driver is suggestable for networ, applications.
Advantages:
#t is a fastest driver among all the drivers available in the mar,et.
To use Type 3 driver in our )dbc applications it is not re.uired to install odbc
native library and database native library.
#t is very much suitable for networ, applications.
Dis advantages:
This driver is not suitable for simple )dbc applications.
This driver re.uires minimum 3;Tier Architecture.
*hen compared to Type6 and Type' drivers.. Type3 driver is efficient and
portable. But when compared to Type: driver$ Type3 driver is not portable.
Type 4 Driver:
o This driver is also called as pure )ava driver i.e$ this driver was
completely implemented by using )ava technology.
o *hen compared to Type6$ Type' and Type3 drivers.. Type: driver is
portable driver.
o Type: driver can be used for any ,ind of applications.
o Type: driver is a cheapest driver when compared to all the drivers
that<s why it is fre.uently used driver.
#: What is JDBC and What are the ste"s to write a JDBC a""lication?

The process of interacting with the database from a )ava application is called as
1DB21ava Database 2onnectivity!
To interact with the database from a )ava application we will use the following five
steps.
6. load and register the driver.
'. +stablish a connection between )ava application and the database.
3. prepare either statement ob)ect or /reparedStatement ob)ect or
2allebleStatement ob)ect as per the application re.uirements.
:. write and e0ecuter the s.l .ueries.
=. terminate the connection which we have established.
$: How to load a JDBC drier?
o #n general sun Microsystems has provided Driver interface for this all
the database vendors has provided their own implementation.
o #f we want to use the database vendor provided Driver implementation
to our )dbc application$ first we need to ma,e the availability of the
respective Driver<s .class file to 1>M$ for this we need to set class
path environment variable to the location where we have the driver
implementation.
o Sun Microsystems is also provided an implementation to the Driver
interface in the form of 1dbc(dbcDriver class as part of the )ava
software.
o #f we want to use 1dbc(dbcDriver in our )dbc applications no need to
set class path environment variable. *hy because it was already
available in the )ava software<s pre;defined library.
o 1dbc(dbcDriver internally depends on the mocrosoft product (dbc
driver. #f we want to use the 1dbc(dbcDriver in our )dbc applications
first we must configure (dbc driver$ for this we will use the following
path.
Start? conrlol panel ? performance and maintenance ? administrative tools ? data
source(dbc!? user dsn ? clic, on Add ? select microsofr (dbc for oracle ? finish ?
provide data source name only ? clic, on o, ? o,.
To load the driver<s class byte code to the memory we will use the following
method.
/ublic void for3ameString class name!
Eg: 2lass.for3ame4sun.)dbc.odbc.1dbc(dbcDriver5!@
*here for3ame! is a static method$ which can be used to load the respective
driver class byte code to the memory.
+ach and every driver class has already a static bloc, at the time of loading the
respective driver class byte code to the memory automatically the available
static bloc, could be e0ecuted$ by this DriverManager.registerDriverA.!
method will be e0ecuted as part of the static bloc,.
By the e0ecution of the registerDriverA.! method automatically the specified
driver will be register to the )dbc application.
#f you want to design any )dbc application$ we need to use some pre;defined
library$ which was provided by the 1dbc A/# in the form of )ava.s.l pac,age$
that<s why we need to import )ava.s.l pac,age in our )dbc application.
ote:! The best alternative for 2lass.for3ame..! is
DriverManagre.registerDrivernew sun.)dbc.odbc.1dbc(dbcDriver!!@
To register the driver.
%: How to establish a Database connection between &aa a""lication and
Database?
#f we want to establish a connection between )ava application and the database we
will the following piece of code.
"onnection con#
Driver$anager%get"onnection&'(dbc:odbc:nag)*)nag)*)system)*)manager)+,
*here get2onnectin! is a static method from DriverManager class$ which can be
used to return connection ob)ect.
': -asica..y "onnection is an interface* how get"onnection&+ wi.. create an
ob(ect for
"onnection interface?
Ans: 2onnection is an interface from )ava.s.l pac,age$ for which get2onnectionB!
was return an anonymous inner class ob)ect of the 2onnection interface.
ote:! Anonymous inner class is a nameless inner class$ which can be sued to
provide an implementation either for the interfaces or for abstract classes.
Eg: interface #
/
void m6!@
0
2lass (uter
/
# i C new #!/
public void m6!
/

0
public void m'!
/
0
0
0
(uter o C new (uter!@
o.i.m6!@ D correct
o.i.m'!@ D wrong
get2onnectionB! is a static method from DriverManager class$ which
will call internally connect! method$ this connect! will establish a virtual soc,et
connection in between the )ava application and the database.
(: What is the require!ent to use )tate!ent ob&ect?
After establishing a connection between )ava application and the database we
need to write the s.l .ueries and we need to e0ecute them.
To e0ecute the s.l .ueries we will use some pre;defined library$ which was
defined in the form of Statement ob)ect$ /reparedStattement ob)ect and
2allableStatement ob)ect.
As per the application re.uirements we need to create either Statement ob)ect
or 2allableStatement ob)ect and /reparedStatement ob)ect.
To create Statement ob)ect dwe will use the following method from
connection ob)ect.
public Statement createStatement!
Eg: Statement st C con.createStatement!@
E: How to execute )*+ *ueries ,ro! a &aa a""lication?
To e0ecute the s.l .ueries we will use the following methods from Statement ob)ect.
st.e0ecute%ueryA!
st.e0ecuteFpdateA!
st.e0ecuteA!
1-: What are the di,,erences between execute*uery./01 execute2"date./0 and
execute./0
!ethods?
Ans: where e0ecute%uery! can be used to e0ecute selection group s.l .ueries to
fetch the data from database.
*hen we use selection group s.l .uery with e0ecute%uery! then 1>M will send that
s.l .uery to the database engine$ database engine will e0ecute it$ by this database
engineDB+! will fetch the data from database and send bac, to the )ava application.
1ava is a purely ob)ect oriented technology. That<s why the )dbc application will
maintain the fetched data from database$ in the form of an ob)ect at heap memory$
called as ResultSet ob)ect.
p1b.ic 2es1.t3et e4ec1te51ery&3tring s6.61ery+
where e0ecuteFpdate! can be used to e0ecute updation group s.l .uery to
update the database. *hen we provide updation group s.l .uery as a parameter to
e0ecuteFpdate!$ then 1>M will send that s.l .uery to DB+$ here DB+ will e0ecute it
and perform updations on the database$ by this DB+ will identify the number of
records got updated value called as 4records updated count5 and return bac, to the
)ava application.
p1b.ic int e4ec1te7pdate&3tring s6.61ery+
where e0ecute! can be used to e0ecute either selection group s.l .ueries or
updation group .ueries.
*hen we use selection group s.l .uery with the e0ecute! then we will get
ResultSet ob)ect at heap memory with the fetched data. But e0ecute! will return
4true5 as a Boolean value.
*hen we use updation group s.l .uery with e0ecute! then we will get 4
records updated count value5 at )dbc application. But e0ecute! will return 4false5 as a
Boolean value.
p1b.ic boo.ean e4ec1te&3tring s6.61ery+
11: How to create a table dyna!ically ,ro! a &dbc a""lication?3
??import section
import )ava.s.l.G@
import )ava.io.G@
public class 2reateTable+0
H
public static void mainStringIJ args!throws +0ception
H
??create buffered reader ob)ect
BufferedReader br C new BufferedReadernew
#nputStreamReaderSystem.in!!@
??load and register the driver
2lass.for3ame4sun.)dbc.odbc.1dbc(dbcDriver5!@
??establish connection
2onnection con C
DriverManager.get2onnection4)dbc"odbc"nag5$5system5$5durga5!@
??create statement ob)ect
Statement st C con.createStatement!@
??ta,e table name as dynamic input
System.out.println4+nter table name5!@
String tname C br.read&ine!@
??e0ecute s.l .uery
St.e0ecuteFpdate4create table59tname95eno number$ename
varchar'68!$esal number$eaddr varchar'68!!5!@
System.out.println4table created successfully5!@
??closing the connection
con.close!@
K
K
12: How to insert records into a table ,ro! a JDBC a""lication?
import )ava.s.l.G@
import )ava.io.G@
public class #nsertTable+0
H
public static void mainStringIJ args! throws +0ception
H
BufferedReader br C new BufferedReadernew
#nputStreamReaderSystem.in!!@
2lass.for3ame4oracle.)dbc.driver.(racleDriver5!@
2onnection con C
DriverManager.get2onnection4)dbc"oracle"thin"Llocalhost"6='6"0e5$5system5$5durg
a5!@
Statement st C con.createStatement!@
whiletrue!
H
System.out.println4+nter emp number5!@
#nt eno C #nteger.parse#ntbr.read&ine!!@
System.out.println4+nter emp name5!@
String ename C br.read&ine!@
System.out.println4+nter emp sal5!@
Mloat esal C Mloat.parseMloatbr.read&ine!!@
System.out.println4+nter emp address5!@
String eaddr C br.read&ine!@
st.e0ecuteFpdate4insert into emp6
values49eno95$<59ename95<$59esal95$<59eaddr95<!5!@
System.out.println4read successfully inserted5!@
System.out.println4one more recordIy?nJ!@
String option C br.read&ine!@
#foption.e.uals4n5!!
brea,@
K
K
K
13: How to u"date a table ,ro! a &dbc a""lication?3
import )ava.s.l.G@
public class FpdateTable+0
H
public static void mainStringIJ args!throws +0ception
H
??load n register the driver in alternative way to 2lass.for3ame
DriverManager.registerDrivernew oracle.)dbc.driver.(racleDriver!!@
2onnection con C
DriverManager.get2onnection4)dbc"oracle"thin"Llocalhost"6='6"0ee5$5system5$5dur
ga5!@
Statement st C con.createStatement!@
int update2ount C st.e0ecuteFpdate4update emp6 set esal C esal9=88 where
esalNE8885!@
System.out.println4records updatedAA..59update2ount!@
con.close!@
K
K
1#: How to delete records ,ro! a table ,ro! &dbc a""lication?3
import )ava.s.l.G@
public class DeleteTable+0
H
public static void mainStringIJ args!throws +0ception
H
2lass.for3ame4oracle.)dbc.driver.(racleDriver5!@
2onnection con C
DriverManager.get2onnection4)dbc"oracle"thin"Llocalhost"6='6"0e5$5system5$5durg
a5!@
Statement st C con.createStatement!@
int update2ount C sst.e0ecuteFpdate4delete from emp3 where esalOCP8885!@
System.out.println4records deletedAAA59update2ount!@
con.close!@
K
K

1$:What is !ent by 4esult)et ob&ect and How to 5etch the Data ,ro! Database?3
4esult)et:6
ResultSet is an (b)ect which can be used to maintain the fetched data from database
in the 1DB2 applications

*hen we e0ecute a selection group s.l .uery$ either with e0ecute%uety! or with
e0ecute! automatically a ResultSet ob)ect will be created at heap memory with the
fetched data from database.
To get the ResultSet ob)ect reference directly we will use e0ecute%uery..!.
*hen we create a ResultSet ob)ect automatically a cursor will be create called
as 4ResultSet cursor5 to read the data from ResultSet ob)ect.
*hen we create the ResultSet ob)ect by default ResultSet cursor will be
created before the first record.
#f we want to read the data from ResultSet ob)ect every time we need to chec,
whether the ne0t record is available or not. #f the ne0t record is available
automatically we need to move that ResultSet cursor to ne0t record position.
To perform this wor, we will use the following method from ResultSet
interface.
public boolean ne0t!
After getting ResultSet cursor to a record position then we need to get the data
from respective fields of the particular record$ for this we will use following
method.

public 000 getQ00int fno!
or!
public 000 getQ00String fname!
where 000 is byte$ shor$ int$ long$ float$ double$ char.
Eg: whilers.ne0t!!
/
System.out.printlnrs.get#nt6!95 59rs.getString'!95 59rs.getMloat3!95
59rs.getString:!!@
0

The fo..owing e4amp.e demonstrates how to fetch the data from database
thro1gh 2es1.t3et ob(ect%
import )ava.s.l.G@
public class Metch+0
H
public static void mainStringIJ args!throws +0ception
H
2lass.for3ame4sun.)dbc.odbc.1dbc(dbcDriver5!@
2onnection con C DriverManager.get2onnection4)dbc"odbc"nag5$5system5$5durga5!@
Statement st C con.createStatement!@
ResultSet rs C st.e0ecute%uery4select G from emp65!@
System.out.println4+3( +3AM+ +SA& +ADDR5!@
System.out.println4GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG5!@
whilers.ne0t!!
H
System.out.printlnrs.get#nt6!9559rs.getString'!95
59rs.getMloat3!95 59rs.getString:!!@
K
K
K
1%:7n8eneral execute.0 !ethod can be used to execute selection 8rou" )*l queries
,or 8ettin8 the data ,ro! Database 1 but execute.0 return a boolean alue true so
here how it "ossible to ,etch the data ,ro! database?
+0ecute! can be used to e0ecute both selection group s.l .uery and updation
group s.l .uery.
#f we use e0ecute! to e0ecute a selection group s.l .uery then DB+Database
engine! will e0ecute that s.l .uery and send bac, the fetched data from
database to )ava application. 3ow )ava application will prepare a ResultSet
ob)ect with the fetched data but e0ecute! will return 4true5 as a Boolean
value.
At this situation to get the reference of the ResultSet ob)ect e0plicitily$ we will
use the following method from Statement ob)ect.
public ResultSet getResultSet!
Eg: boolean b C st.e0ecute4select G from emp65!@
System.out.printlnb!@
ResultSet rs C st.getResultSet!@
1':7n8eneral execute.0 !ethod can be used to execute u"datation 8rou" )*l
queries ,or u"datin8 the data on Database 1 but execute.0 return a boolean alue
,alse so here how it "ossible to 8et the records u"dated count alue.int alue0?
+0ecute! can be used to e0ecute both selection group s.l .ueries and updation
group s.l .ueries.

#f we use e0ecute! to e0ecute an updation group s.l .uery then DB+ will
e0ecute it and send bac, the records updated count value to the )ava
application. But e0ecute! will return 4false5 as a Boolean value. At this
instance$ to get the records updated count value e0plicitly we will use the
following method from Statement ob)ect.
public int getFpdate2ount!
Eg: import )ava.s.l.G@
public class Metch+0
H
public static void mainStringIJ args!throws +0ception
H
2lass.for3ame4sun.)dbc.odbc.1dbc(dbcDriver5!@
2onnection con C DriverManager.get2onnection4)dbc"odbc"nag5$5system5$5durga5!@
Statement st C con.createStatement!@
boolean b C st.e0ecute4update emp6 set esalCesal9=88 where esalNE8885!@
System.out.printlnb!@
int update2ount C st.getFpdate2ount!@)
System.out.printlnupdate2ount!@
K
K
1(: 7, we use selection 8rou" )*+ query to execute2"date.0 1what ha""ened?
#f we use selection group s.l .uery as a parameter to e0ecuteFpdateA! then
1>M will send that s.l .uery to the DB+$ DB+ will fetch the data and send
bac, to the )ava application here )ava application will store the fetched data in
the form of ResultSet ob)ect. But e0ecuteFpdate! is e0pecting records
updated count value.
Due to this contradiction 1>M will rise an e0ception li,e
)ava.lang.S%&+0ception.
#f we handle the above e0ception properly then we will get ResultSet ab)ect and we
will get the data from Database
import )ava.s.l.G@
class Test
H
public static void mainStringIJ args!
H
Statement stCnull@
try
H
2lass.for3ame4sun.)dbc.odbc.1dbc(dbcDriver5!@
2onnection con C
DriverManager.get2onnection4)dbc"odbc"nag5$5system5$5durga5!@
st C con.createStatement!@
boolean b C st.e0ecuteFpdate4select G from emp65!@
K
catch+0ception e!
H
ResultSet rsCst.getResultSet!@
System.out.println4+3( +3AM+ +SA& +ADDR5!@
System.out.println4GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG5!@
whilers.ne0t!!
H
System.out.printlnrs.get#nt6!9559rs.getString'!95
59rs.getMloat3!95 59rs.getString:!!@
K
e.printStac,Trace!@
K
K
19: 7, we use u"datation 8rou" )*+ query to execute*uery.0 1what ha""ened?
#f we use updation group s.l .uery as a parameter to e0ecute%uery! then
1>M will send that s.l .uery to the DB+$ DB+ will perform updations on the
database and send bac, records updated count value to the )ava application.
But here e0ecute%uery! is e0pecting ResultSet ob)ect reference.
Due to this contradiction 1>M will rise an e0ception li,e
)ava.lang.S%&+0ception.

import )ava.s.l.G@
class Test
H
public static void mainStringIJ args!
H
Statement stCnull@
try
H
2lass.for3ame4sun.)dbc.odbc.1dbc(dbcDriver5!@
DriverManager.get2onnection4)dbc"odbc"nag5$5system5$5durga5!@
st C con.createStatement!@
boolean b C st.e0ecute%uery4update emp6 set esalCesal96888 where esal
N688885!@
K
catch+0ception e!
H
int countCst.getFpdate2ount!@
System.out.printlncount!@
e.printStac,Trace!@
K
K
2-: What is !ent by 4esult)et and What are the ty"es o, 4esult)ets are aailable in
JDBC a""lication?

#n )dbc applications ResultSets could be classified in the following two ways.
8n the basis of 2es1.t3et privi.i9ations &"onc1rancy+:!

There are ' types of ResultSets.
o Read only ResultSet
o Fpdatable ResultSet
Read only ResultSet"; #t is a ResultSet$ which will allow the users to read the
data only. To refer this ResultSet$ we will use the following constant from ResultSet
interface.
public static final int 2(32FRBR+ADB(3&R@
Fpdatable ResultSet"; #f is a ResultSet ob)ect$ which will allow users to perform
some updations on its content. To refer this ResultSet we will use the following
constant from ResultSet interface.
public static final int 2(32FRBF/DATAB&+@
2+8n the basis of the 2es1.t3et c1rsor movement:!
There are ' types of ResultSets.
o Morward only ResultSet
o Scrollable ResultSet
Morward only ResultSet"; #t is a ResultSet ob)ect$ which will allow the users to iterate
the data in any forward direction. To refer this ResultSet ob)ect we will use the
following constant from ResultSet interface.
public static final int TR/+BM(R*ARDB(3&R@
Scrollable ResultSet"; These are the ResultSet ob)ects$ which will allow the users to
iterate the data in both forward and bac,ward directions.
There are ' types of Scrollable ResultSets.
Scroll sensitive ResultSets
Scroll in sensitive ResultSets.
21: What is the difference between 3cro..3ensitive 2es1.t3et and
3cro..:nsensitive 2es1.t3ets?
Ans: Scroll sensitive ResultSet is a ResultSet ob)ect$ which will allow the later
updations from database automatically after creating it. To refer this ResultSet we will
use the following constant.
public static final int TR/+BS2R(&&BS+3S#T#>+@
Scroll insensitive ResultSet is a ResultSet ob)ect$ which will not allow later
updations from database after creating it. To refer this ResultSet we will use the
followingconstant from ResultSet interface.
public static final int TR/+BS2R(&&B#3S+3S#T#>+@
22:What is the de,ault 4esult)et ty"e in JDBC a""lication and How it is "ossible to
create a s"eci,ic ty"e o, 4esult)et ob&ect?
The default ResultSet type in the )dbc applications is Read only and forward
only.
#n )dbc applications we are able to specify the following types of the ResultSet
combination to any particular ResultSet.

o read;only$ forward only
o read;only$ scroll sensitive
o read;only$ scroll insensitive
o updatable$ forward only
o updatable$ scroll sensitive
o updatable$ scroll insensitive
if we want to specity a particular type to the ResultSet ob)ect then we should
use either of the above constants combination as a parameter to
createStatement! method$ for this we will use the following method.

public Statement createStatementint forward ? ScrollSensitive ? Scroll#nsensitive$ int
readonly ? updatable!
Eg: Statement st C con. createSensitiveResultSet.TR/+BS2R(&&BS+3S#T#>+$
ResultSet.2(32FRBF/DATAB&+!@
ResultSet rs C con.e0ecute%ueryA.!@

23:How to iterate the data ,ro! )crollable 4esult)et ob&uect in both ,orward and
bac:word direction?
to iterate the data in forward direction from a ResultSet ob)ect we will use the
following ' methods.
public Boolean ne0t!
public 000 getQ00int fieldno.!
*here 000 may be byte$ short$ char$ int$ long$ float$ double.
To iterate the data in bac,ward direction from Scrollable ResultSet ob)ect we
will use the following ' methods.

public Boolean previous!
public 000 getQ00int fieldno!
*here previous! is a Boolean method$ which can be used to chec, whether
the previous record is available or not$ if it is available then cursor will be moved to
previous record position.

The fo..owing e4amp.e demonstrates how to iterate the data in both forward and
bac;ward direction from the 2es1.t3et ob(ect
import )ava.s.l.G@
public class ScrollRes+0
H
public static void mainStringIJ args!throws +0ception
H
2lass.for3ame4sun.)dbc.odbc.1dbc(dbcDriver5!@
2onnection con C DriverManager.get2onnection4)dbc"odbc"nag5$5system5$5durga5!@
Statement st C
con.createStatementResultSet.TR/+BS2R(&&BS+3S+#T#>+$ResultSet.2(32FRB
F/DATAB&+!@
ResultSet rs C st.e0ecute%uery4select G from emp65!@
System.out.println4data in forward direction5!@
System.out.println4+3( +3AM+ +SA& +ADDR5!@
System.out.println4GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG5!@
*hilers.ne0t!!
H
System.out.printlnrs.get#nt6!95 59rs.getString'!95 59rs.getMloat3!95
59rs.getString:!!@
K
System.in.read!@
System.out.println4data in bac,ward direction5!@
System.out.println4+3( +3AM+ +SA& +ADDR5!@
System.out.println4GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG5!@
*hilers.previous!!
H
System.out.printlnrs.get#nt6!95 59rs.getString'!95 59rs.getMloat3!95
59rs.getString:!!@
KKK
2#: how to generate 3cro..3ensitive 2es1.t 3et and how to ref.ect the .ater
1pdations from database a1tomatica..y to the 2es1.t3et ob(ect?
import )ava.s.l.G@
public class Test
H
/ublic static void mainStringIJ args!throws +0ception
H
2lass.for3ame4sun.)dbc.odbc.1dbc(dbcDriver5!@
2onnection con C DriverManager.get2onnection4)dbc"odbc"nag5$5system5$5durga5!@
Statement st C
con.createStatementResultSet.TR/+BS2R(&&BS+3S+#T#>+$ResultSet.2(32FRB
F/DATAB&+!@
ResultSet rs C st.e0ecute%uery4select G from emp65!@
rs.ne0t!@
System.out.println4old salary emp666AA.59rs.getMloat3!!@
System.in.read!@??application is in pause$ perform database updations
Rs.refreshRow!@
System.out.println4new salary of emp666AA..59rs.getMloat3!!@
K
K *here refreshRow! is a method from Scrollable ResultSet ob)ect$ which can be
used to refresh the current row in the ResultSet ob)ect to allow the later updations
from database. /rototype of this method is
public void refreshRow!
2$: <ow to insert records into Database throws 7pdatab.e 2es1.t3et?
#f we want to insert a new record on to the database through Fpdatable ResultSet
ob)ect$ we will use the following steps.
3tep1: Set the Fpdatable ResultSet ob)ect with fetched data.
3tep2: Move ResultSet cursor to the end of the ResultSet ob)ect$ where we need to
ta,e a buffer to hold new records data temporarily$ for this we use the following
method from updatable ResultSet ob)ect.

public void moveTo#nsertRow!
3tep3: #nsert new records data on to the buffer temporarily at Fpdatable ResultSet
ob)ect for this we will use the following method format.
public void updateQ00int fieldno$000 value!
*here 000 may be byte$ short$ int$ char$ double$ float$ long.
3tep4: Ma,e the temporary insertion as the permanent insertion in Fpdatable
ResultSet ob)ect as will as in database$ for this we will use the following method.
public void insertRow!
The fo..owing e4amp.e demonstrates how to insert no% of records onto the
database thro1gh 7pdatab.e 2es1.t3et ob(ects%

import )ava.s.l.G@
import )ava.io.G@
public class FpdateRes+0
H
public static void mainStringIJ args!throws +0ception
H
2lass.for3ame4sun.)dbc.odbc.1dbc(dbcDriver5!@
2onnection con C DriverManager.get2onnection4)dbc"odbc"nag5$5system5$5durga5!@
Statement st C
con.createStatementResultSet.TR/+BS2R(&&BS+3S+#T#>+$ResultSet.2(32FRB
F/DATAB&+!@
ResultSet rs C st.e0ecute%uery4select G from emp65!@
BufferedReader br C new BufferedReadernew #nputStreamReaderSystem.in!!@
rs.moveTo#nsertRow!@
whiletrue!
H
System.out.println4enter employee number5!@
int eno C #nteger.parse#ntbr.read&ine!!@
System.out.println4enter employee name5!@
String ename C br.read&ine!@
System.out.println4enter employee salary5!@
float esal C Mloat.parseMloatbr.read&ine!!@
System.out.println4enter employee address5!@
String eaddr C br.read&ine!@
rs.update#nt6$eno!@
rs.updateString'$ename!@
rs.updateMloat3$esal!@
rs.updateString:$eaddr!@
rs.insertRow!@
System.out.println4record successfully inserted5!@
System.out.println4one more recordIy?nJ!@
String option C br.read&ine!@
ifoption.e.uals4n5!!
brea,@
K
K

2%: <ow to perform 1pdations on Database throws 7pdatab.e 2es1.t3et?
By using Fpdatable ResulSet ob)ect we are able to perform some updations on to the
database. To perform updations on to the database through Fpdatable ResultSet ob)ect
we will use the following steps.
3tep1: Set the Fpdatable ResultSet ob)ectd with the fetched data.
3tep2: Move ResultSet cursor to a record where we want to perform updations$ for
this we will use the following method.
public void absoluteint recordno.!
3tep3: /erform Temporary updations on to the particular record$ for this we will use
following method.
public void updateQ00int fieldno$000 value!
3tep4: Ma,e the temporary updation as a parmenent updation on to the Fpdatable
ResultSet ob)ect as well as to the database. Mor this we will use the following method.
public void updateRow!
The fo..owing e4amp.e demonstrates how to perform 1pdations on to the
database thro1gh 7pdatab.e 2es1.t3et ob(ect%
import )ava.s.l.G@
public class FpdateRes+06
H
public static void mainStringIJ args!throws +0ception
H
2lass.for3ame4sun.)dbc.odbc.1dbc(dbcDriver5!@
2onnection con C DriverManager.get2onnection4)dbc"odbc"nag5$5system5$5durga5!@
Statement st C
con.createStatementResultSet.TR/+BS2R(&&BS+3S+#T#>+$ResultSet.2(32FRB
F/DATAB&+!@
ResultSet rs C st.e0ecute%uery4select G from emp65!@
rs.absolute3!@
float newsal C rs.getMloat3!9=88@
rs.updateMloat3$newsal!@
rs.updateRow!@
K
K
2':what is !eant by 4esult)et;etaData ?How to 8et <he 4esult)et !etadata o, a
4esult)et ob&ect?
Data about the data is called as Metadata. Similarily data about the data available in
ResultSet ob)ect called as 4ResultSet Metadata5.

ResultSet Metadata includes the number of columns of a table in ResultSet
ob)ect$ all the column names$ column datatypes and the column display si-es.
To get the ResultSet Metadata ob)ect we will use the following method from
ResultSet ob)ect.
public ResultSetMetaData getMetaData!
To get the number of columns available in ResultSet ob)ect we will use the
following method from ResultSetMetaData ob)ect.

public int get2olumn2ount!
To get the name of a particular column$ we will use the following method.

public String get2olumn3ameint fieldno!
To get the column datatype of a particular column$ we will use the following
method

public String get2olumnType3ameint fieldno!
To get the column display si-e of a particular column we will use the
following method.
public int get2olumnDisplaySi-eint fieldno!
The fo..owing e4amp.e demonstrates how to get 2es1.t3et$etaData from a
2es1.t3et ob(ect
import )ava.s.l.G@
public class ResultSetMD
H
public static void mainStringIJ args!throws +0ception
H
2lass.for3ame4sun.)dbc.odbc.1dbc(dbcDriver5!@
2onnection con C DriverManager.get2onnection4)dbc"odbc"nag5$5system5$5durga5!@
Statement st C con.createStatement!@
ResultSet rs C st.e0ecute%uery4select G from emp65!@
ResultSetMetaData rsmd C rs.getMetaData!@
int count C rsmd.get2olumn2ount!@
System.out.println4number of columns......59count!@
forint iC6@iNCcount@i99!
H
System.out.printlnrsmd.get2olumn3amei!95 49rsmd.get2olumnType3amei!95
49rsmd.get2olumnDisplaySi-ei!!@
System.out.println!
K
K
K
2(: how to disp.ay the data with the respective fie.d names
import )ava.s.l.G@
public class RSMD6
H
public static void mainStringIJ args!throws +0ception
H
2lass.for3ame4sun.)dbc.odbc.1dbc(dbcDriver5!@
2onnection con C DriverManager.get2onnection4)dbc"odbc"nag5$5system5$5durga5!@
Statement st C
con.createStatementResultSet.TR/+BS2R(&&BS+3S+#T#>+$ResultSet.2(32FRB
F/DATAB&+!@
ResultSet rs C st.e0ecute%uery4select G from emp65!@
ResultSetMetaData rsmd C rs.getMetaData!@
System.out.printlnrsmd.get2olumn3ame6!95 49rsmd.get2olumn3ame'!95
49rsmd.get2olumn3ame3!95 49rsmd.get2olumn3ame:!!@
System.out.println4GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG5!@
whilers.ne0t!!
H
System.out.printlnrs.get#nt6!95 49rs.getString'!95 4rs.getMloat3!95
49rs.getString:!!@
K
K
K
29: What are the differences between 3tatement and =repared3tatement?
.or0
Te.. me the sit1ations where we sho1.d go for =repared3tatement over 3tatement
ob(ect%
Ans:
*hen we have a re.uirement to e0ecute same ,ind of s.l .uery in the ne0t
se.uence then we should go for /reparedStatement over Statement ob)ect.
Mor the above re.uirement if we use Statement ob)ect$ every time e0ecution of
the same s.l .uery DB+ must perform .uery to,eni-ation$ .uery parsing$
.uery optimi-ation and .uery e0ecution.
This approach will increase burden to the DB+. To reduce burden to the DB+
we should go for an alternative. That is /reparedStatement over Statement
ob)ect.
Mor the same re.uirement if we use /reparedStatement ob)ect then for our
complete re.uirement DB+ will go for only one time .uery parsing
to,eni-ation$ parsing$ optimi-ation and e0ecution!@
#f we want to use /reparedStatement ob)ect for the above re.uirement then
we will use following steps.
3tep1: /repare /repareStatement ob)ect by providing generali-ed s.l .uery format
with the re.uired number of parameters$ for this we will use the following method
from Statement ob)ect.
public /reparedStatement prepareStatementString s.l.ueryformat!
Eg: /reparedStatement pst C con.prepareStatement4insert into emp6
valuesT$T$T$T!5!@
*hen 1>M encounters above instruction )vm will pic,up specified
generali-ed s.l .uery format and send to the DB+$ here DB+ will process .uery
format only one time and prepare a Buffer with the specified parameters$ called as
4.uery plan5. As a result /reparedStatement ob)ect will be created with the
parameters at )ava side.
3tep2: Set the values to parameters in /reparedStatement ob)ect. After getting
/reparedStatement ob)ect with parameters$ we need to set some values to perform an
operation$ for this we will use the following method.
public void setQ00int parano$000 value!
where 000 may be byte$ short$ char$ int$ long$ float$ double.
Eg: pst.set#nt6$666!@
pst.setString'$5abc5!@
*hen 1>M encounters the above method then )vm will set the specified
values to the specified parameters at the /reparedStatement ob)ect$ intern that
parameter values could be reflected to .uery plan.
3tep3: Siven an intimation to DB+ to perform the respective operation. After setting
the values to the parameters we should give an intimation to the DB+ e0plicitly
pic,up the values from .uery plan and perform the operation specified in generali-ed
s.l .uery format$ for this we will use the following methods.
#f the generali-ed s.l .uery belongs to selection group then we will use
following method from /reparedStatement ob)ect
public ResultSet e0ecute%ueryA!
#f the generali-ed s.l .uery belongs to updation group then we will use the
following method.
public int e0ecuteFpdateA!
3-: <how to insert n1mber of records into a tab.e thro1gh =repared 3tatement
ob(ect%
import )ava.s.l.G@
import )ava.io.G@
public class /repared#nsert+0
H
public static void mainStringIJ args!throws +0ception
H
2lass.for3ame4sun.)dbc.odbc.1dbc(dbcDriver5!@
2onnection con C DriverManager.get2onnection4)dbc"odbc"nag5$5system5$5durga5!@
/reparedStatement pstC con.prepareStatement4insert into emp6 valuesT$T$T$T!5!@
BufferedReader brC new BufferedReadernew #nputStreamReaderSystem.in!!@
whiletrue!
H
@ K
K
31: how to 1pdate the database thro1gh =repared3tatement ob(ect%
import )ava.s.l.G@
public class /reparedFpdate+0
H
public static void mainStringIJ args!throws +0ception
H
2lass.for3ame4sun.)dbc.odbc.1dbc(dbcDriver5!@
2onnection con C DriverManager.get2onnection4)dbc"odbc"nag5$5system5$5durga5!@
/reparedStatement pst C con.prepareStatement4update emp6 set esal C esal9T *here
esalNT5!@
/st.set#nt6$=88!@
/st.setMloat'$68888.8f!@
#nt count C pst.e0ecuteFpdate!@
System.out.println4no. of records updated"59count!@
K
K
32:how to fetch the data from database thro1gh =repared3tatement ob(ect%
import )ava.s.l.G@
public class FpdateRes+0
H
public static void mainStringIJ args!throws +0ception
H
2lass.for3ame4sun.)dbc.odbc.1dbc(dbcDriver5!@
2onnection con C DriverManager.get2onnection4)dbc"odbc"nag5$5system5$5durga5!@
/reparedStatement pst C con.prepareStatement4select G from emp6 where esalNCT5!@
/st.setMloat6$68888.8f!@
ResultSet rs C pst.e0ecute%uery!@
System.out.println4+3( +3AM+ +SA& +ADDR5!@
System.out.println4GGGGGGGGGGGGGGGGGGGGGGGGGGGGGG5!@
*hilers.ne0t!!
H
System.out.printlnrs.get#nt6!95 49rs.getString'!95 49rs.getMloat3!95
49rs.getString:!!@
K
K
K
33:What is !eant by <ransaction? How it is "ossible to !aintain <ransactions in
JDBC a""lications?
Transaction is nothing but an unit of wor, performed by the applications.
+very transaction should have the following properties.
Atomicity
2onsistency
#solation
Durability
*here atomicity is nothing but perform all the operations or not to perform all
the operations in a transaction. That is every transaction must be in either
success state or failure state.
As part of the )dbc applications when we establish a connection automatically
the connection should have a default nature called as 4auto commit5.
Auto commit in the sense when we send an s.l .uery to the connection then
connection will carry that to the DB+ and ma,e the DB+ to e0ecute provided
s.l .uery and store the results on the database permanently.
The connections default auto commit nature violates the transactions atomicity
property.
To preserve transactions atomicity property we should change the connections
auto commit nature to non;auto commit nature$ for this we will use the
following method.

/ublic void setAuto2ommitBoolean b!
*here bCtrue connection is in auto commit
And bCfalse connection not in auto commit.
#f we use connections non auto commit nature in our )dbc applications then we
must use either commit or rollbac, operations e0plicitily as part of the
transactions.
/ublic void commit!
/ublic void rollbac,!
The fo..owing e4amp.e demonstrates how to maintain the transactions with
atomicity property in the (dbc app.ications%
import )ava.s.l.G@
public class Transaction+0
H
public static void mainStringIJ args!throws +0ception
H
2onnection con C null@
try
H
2lass.for3ame4sun.)dbc.odbd.1dbc(dbcDriver5!@
2on C DriverManager.get2onnection4)dbc"odbc"nag5$5system5$5durga5!@
con.setAuto2ommit4false5!@
Statement st C con.createStatement!@
st.e0ecuteFpdate4insert into emp6 values777$<fff<$7888$<hhh<!5!@
st.e0ecuteFpdate4update emp6 set esal C esal;=88 where esalOC Uabc< 4!@
st.e0ecuteFpdate4delete emp6 where esalNP8885!@
con.commit!@
K
catch+0ception e!
H
con.rollbac,!@
System.out.printlne!@
K
K
K
3#:What is !eant by )ae=oint?How to use )ae"oints in JDBC a""lications?
Save point is a concept introduced by )dbc 3.8 which can be used to bloc, a
set of instructions e0ecution in the transactions committing operation.
To set a save point we will use the following method.
public Save/oint setSave/oint!
To bloc, a set of s.l .ueries e0ecution prior to the save point we will use the
following method.
public void rollbac,savepoint s!
To release a savepoint we will use the following method
public void releaseSave/oint!@
Save/oint concept could not be supported be type6 driver$ it could be
supported by type: driver.
+ven type : driver is supporting up to setSave/oint! and rollbac,! $ not
releaseSavepoint!@

Eg:
import )ava.s.l.G@
public class Save/oint+0
H
public static void mainStringIJ args!throws +0ception
H
2onnection con C null@
try
H
2lass.for3ame4oracle.)dbc.driver.(racleDriver5!@
con C
DriverManager.get2onnection4)dbc"oracle"thin"Lloca)host"6='6"0e5$5system5$5durg
a5!@
con.setAuto2ommit4false5!@
Statement st C con.createStatement!@
st.e0ecuteFpdate4insert into emp6 values666$<fff<$7888$<hhh<!5!@
savepoint spC con.Savepoint!@
st.e0ecuteFpdate4insert into emp6 values'''$<ggg<$P888$<iii<! 4!@
con.rollbac,sp!@
st.e0ecuteFpdate4insert into emp6 values333$<hhh<$E888$<)))<!5!@
con.commit!@
K
catch+0ception e!
H
con.rollbac,!@
System.out.printlne!@
K
K
K

Вам также может понравиться