0% found this document useful (0 votes)
3 views

Advance-Java-JDBC-1

The document provides an overview of various Java editions, including Standard Edition (SE), Enterprise Edition (EE), and Micro Edition (ME), detailing their purposes and applications. It discusses the Model-View-Controller (MVC) architecture, JDBC API for database connectivity, and the importance of Maven for project management and dependency management. Additionally, it covers database types, CRUD operations, and the process of establishing database connections in Java applications.

Uploaded by

kp.at.workplace
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Advance-Java-JDBC-1

The document provides an overview of various Java editions, including Standard Edition (SE), Enterprise Edition (EE), and Micro Edition (ME), detailing their purposes and applications. It discusses the Model-View-Controller (MVC) architecture, JDBC API for database connectivity, and the importance of Maven for project management and dependency management. Additionally, it covers database types, CRUD operations, and the process of establishing database connections in Java applications.

Uploaded by

kp.at.workplace
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

DATE

yper of Editions
DTava SBandord Ecition
(OTere JAYA,JAVA SE
I) Tava Enterom'se EdiEicm.
ADVANcE TAVA JEE, J2EE
11) Toya Mico Edition
Java Mobile Edition
Hhe Purpose of different Editions?
Tava Standard EdiH¡n (7E)
->
Sng is a lbraly of Tava
> Swin refers to Htle Tava Swing Librasy
whic is
set of Singre.
gaphical er înte face
CGur) camponents asl tools for buding
dosktopapplications
#Applet
’ Applet PE wed to perform Some hunchion
-> An apple i a Small coaompute pragTan.
thatper forms Speciic task
DS ing TSE ,We can build,
)Standalone. Application
) Sockek Applicatiom.

IÆ application necde to be installed to be able to


wse platforem, such kind of applieakin i
known a stondalome applicotien.
D T2EE (Enterprise Edikin)
Web applicotion- Application which i going to be
daplayed ServeC
) To build weh apps we. need hela of "seeylet Ar"
t Instagram, Amaz0n.
) JME CTAYA Mieno Edlition )-desinad for resourte-const-re
SERVER a machine with
with higber confaurabion.
TMETava Miero Edi bton) Subse of the Tava
>TaVa Miero Edition
platform that fs designed for resource- carned
deusces a s mobile- phones
Eg' opera Mini, Nokia Maps (for merly Nokia Ovi Maps)
Googe Maps fo mobile (eary vession
DATE

MVCModel-View-(ontoller
-send data
tibiates
Bain via qetters
Archteture
Controller
Reguest
data Serd
odata vfew- Driver
Model- Modi
U (ontoller -Buires

Mode Data

Repone user
Controller (Brain)> Corntrols decides ho data is displayed
Model (Data Modify) - Data Logic with
View (User Inter taca)’ gelters, settors, toskina
Represerts curent mod state
It takes înput from wer
-) MVc, wich standy for Model -
Vien-Controler
It is a software arhitectura pattun
sed in the design and commony
development f applRcafons
Paricularly
d deskop
in the
appieati on.
Comtext o eb applfcahon
Tt
It f aa woy to organixe stucture cde.
to enkance maintaiobiliky aaalatyo)
and scalability
Package Dedaration:
Padogs
domain etensin, oganizatonerame, project=n .nam. model
domain- extension. cngonieohonyname,projtch-name.Ve
damain- extension, ongpnz aion name. project.name, control er
t¡ edu. qsp.kns. model, edu,9sp. ms. vie weduqpm toyto
tter.
-Domaun Extension &
Commerçal -oovernment webite
îndian woebeite
onorg anizaion
TOsC-
JDBC
Iova
Tava
DataBaleCopsbettt
’henexer wite
e
with datab
faat paqxanm neud ta cannmuaiakinterface nead
standi ai an
TORO PI
Tava nognam & datoa bale.
between J DBC

TH is tbheoalyAPI which helpe java


J datahase
pagam
Communicate
meanwobile, t alO helpe
back ith jauaapplicatin of databaiete
ngramner

Rrogramming
API - Applicatin Taterface.
An API is set of rules prototols thot
dlefines oAterat softwore Componenh
how aertnt
should interaot with each ohr
Tt provides structured atandarize
fox different aplicaion moldes
4,0 mmunicate exchange olata
Data Datu rawfa ct which descibel
attributes of an entiky.
Data Stcxage Solabioni
Data storage is
Anith whare bow edere informatoni
digilal sydtem
) File Shonage
) Database
'DATE

1ile stTCge Dotabaie


nead
J DBC )) In Cile system it )In database it _pxovides
0x0vide
provides less secuiky more

)No eticient quy )Efficient qucry pra ceit


ike subquey, TOINS
pecertint
Reduendant data
>Fasy Manipulahion updation
can be. ) Redunlant data can
ton
D be ayoided.
pcsent

J Less compezky o
V Iv) Moe
Lacndlald
aandle

t Database medium
Databate is place stutetured
whene gtoe data
Systematic manner

Tupes oE Databae
DRelaticnal Database ctoe
i s a soft ware where we
I
tables er relations.
data
iented databae
Objeck
) I o tuare where wwe ttore
date fom
DATE

t) Grraph Datahae.
) Dishributed Databae
soFtwure which
dictibu
aleng different localions
V) Data Ware houie
I fomausfor fastee quy
execuioo
Large amount
x) No SQL
As
anga
Dotabaje mutiple
Can be

weh- opplicat iomi are giawing exten vel


stored

we are to nosgl database


becuse oe not hane sheuiture
anytime ad d eetra ielele
shuctLre
v1) Cloud Databaue :
Cloud datahaie help ih shuctur
rom-structureddata
uynd claud privalepublie
what DBC API
IE specikicakion pided by QunmicrQ
systems that pxovides standasd abstactiom
Java application witth vartou databases

Enterprise data stored relationadatabe


be accesed ith halp o JDBC API
and mespectire databae Serre
The API pxovides mechanism fox dyna
mically loadine Tava packoga
database h nicate
to ned Applicotion Tava wiSuppore
Crush (rushRF
drer
TRE Tum
odtgnes der Appln
fostqmes API
Tava
TD8C
Oracte driver
orace
interact
ware drfver
sot drirer and TD8C
TDAC A doe How |
queries.
d doeun't apelioalion Java and
Tava
undirstand doesnt DataboAe
API
JDBC
Dataßese Appl Java
halps TD8C does How
gideriag
driver them
Databa with,any connect
ion establisb
Appl"
to Tava helps API DTDBC
DATE
TDBC API oil not covert stadement
into databae undur stahdoble
anguge
So we neo Cmeth ing which Comvert
database understabdab datements into
Rupectire datahase underctandable anquagg
database
Driver softwore will Loalk with reepectire
database
alba il pzovide Driver soltware
Driver softuare wil. be praddad byb
Data Base Vendox
TDRC API i independentof databale
Database daier is dapendent
whereaDatabase
Datahcue

Steps to Connect uith DataRase 2


) Load o Register direr
) Estakbligh Connectfom
) Czeatiom Statement

)Execution SLatement

NClose Conneckiorm
'DAT

Fesizcs&al
Search PgAdmin > run os od ministrator root
pawod

Cmeate Databae
cneate table
Dorop Doatabaye
#MAVEN Project -
Why do we need to Cmrtate MAVEN proie
laile Jog king with TDRc
Creating MAVEA Qrojeck while wrking
TDÁ offers Seveial adontages.
-. 9 Dapendany Management. dowaloadeinclude
Vautam aflcally
MAVEN wils Vautomacally
cies enseike athat buileprajecttione
required dependen ciu
has the Gbyaries
necessary run-time.

Consiutent Project Shucture


MAVEN shucture
follanws standand project mange
4 code
making it mganite
lbase.Tt pranmpts he Useparation of source
Ce4 configuration ilesallowing
A for hetter code separatim, maintainablit
and collaboration witain eam.

Easy Praiect Setup


MAVEN prades arche types, templaes for
jeck template
predefined poect
wich are pnedefioed
diflerent type of appicakim1.
Thre Vare archeypes
archebypes axailable
JDBC projecds dich selup inital
|DaTE

pxoject sheuckuce, configurakin aad olegendeoc


04 eas ta qet ctart
makei quick
with JDRC
prajecke.
GDeperndency: Yersion
Vecsien Management
Contiouaus Takeqraton

MA VEN aming Convention


Yeverre lomain
Group ld qaou or rga
Toidentifies the
nizatiag witeo
domain name

organization demain i "example<com


Lg If
then i b e ’ cena example
ArtifactId : Poroject Name
The id epteots the
aeeh artifact id
specific preject within the Qroup.
I i the nam that
wil used to ideotily it
be withis
oup.
Typically ar bifach id i sionply find
f
ame whot
lowercas
any
ofproiect
paces oe speigd
'DATE

Cott n ’ Select MAVEN project ’ eom.qsp’ myistloe

t What it
dependency
We necd to modify i "pom.xml" ile by
adding dupendancies int it.
In conlert with MAVEN project.dapendana
Tn
in the pom.xm" ile rfes o external
ibrary r module tat
madude that your praject elies
Intide "pom.ximl" in <dependepcies >
<ldependencies we an oefinc dlapendencdes.
ieWe nead to add dapendencies to
depeoding
datahale that we
establsh Connechi¡n witb.
In Caie we are
we will Poclgre dependenee
’Ovunerahibties
mniaeposikeny postamigl TDBCpastoses ’ more wsage
Diver ’latest versio

How to add depen dencies into TAYA Projeet


) Go to_ goagle -- search DOw.mvnrepasitonyacm
) Search atabase dier- TOBG pactgnegl Drise
M). SELECT with R latest version
Iñ) sELECT latest
V) Go to MAVEN tab mattoehabilitica ,most uiaae
versim ,

u) sELECT dependan ces k


V) Addit in pom.xml Ale.
vu) in <dapendancies) tag
-I

Program to insert data and theing S


5step:'
st .
)Load.ar Register Driverir
Clas. forHame ("ora-postgrcsgl. Dier ;
foName ) e SA tatic methed
Buklicarqument
which takes String ai an argumo
’ We
have toto pas Diver path af
respectivt databJe
’ This
lhi methad thro$ classNot Fou ndkx epb
exceptian, it Can be handled loy thro
( trycatch mechanicm

) Establish Connection -
Connectin connectin = DriverManager. qet ConneeEion

’ To estabishonoecticn with databae, e have


methodnamd get Coaneckim (Sting ul, Shin uer
It averloaded metho.
a
’ DriverManager. qet Connectim (uel, wsee, pwd), Tbis
method is preent în Driver Manager.
DrivcManuger helper cas
qet Conneckicn) static method
qetlonnectin () method asking thnee
eO url- unirersal resowrce locator
Shing uelydbc ipostresql:tl localhost S432/DRnam
() user, - wwername ofdatabaie
passwrd databae paurwerd.
Tui nethod retwrns Connetin chËect (Congeton)
DATE

) Crreaion o 8tatement:
-).To cse te statement we Can Connechin
abject
IE netwns staltment object.
Skaktment stateonent : connectin.create Statmah
v) Exteutin of Statement i
xe cube. qussy statement
statement. execube ();

#Queries for Rasic CRUD operatin :


Koyeste Tabte
abte tablenomg
>tatement. execute ( Quey'
INSERTL
tNTO skudent VALUES(1'Alok)j
wHERE id 2;
wpDATE studont sEI name KATAL

v) Uose Connection :
-> CoDDection. close O:

Retriere Data Prom database


SELEC
To
have method
execate Qucrg Shing
U'named) leuoueluyl)
Te burns OResut seB abject
-paTE'

WhatE Result Set0faterface pmesent io


Resultset
jaa. sa package
reterns boolean
ResultSe -holds data
inde 2

T Shecla
Laila
Alok

Whatdos Reiult Set do olih hes been


Result Set holds data
datahale when we execute
returned from
SELECT query
11) We Can ek ResultE Set objeck hy calig
ResultSet to fetch data bom
We
odatabese
N) ReSultSet acts

)_ResultSet objeck maintains Curser that


points to row of okesult Set.
sed to move
The Dext() method
Curser to next positicn.
Note There re few more methocls the
Result Set to febch econd or data
from Resut set
DATE

frorn doakag
Wehae multipk menode ko fetch data'uwith
dieent datatype
Paramoer
eturnt
columnvauldata
9ek Int Cnt columnindex)HhroMs SqLEXCETIDN
qet Stin (Sting colurmn.ngn) inos GoLEXCE PTI6
qet Double (oub le colemnindex)thtolu SpLEXCEIO
getlong () , ete. colinda ot vutd
columo number
) For thic method, we Can pasS col
which we call index.
Notei Index starte Arom 1. These yet ()
overloaded meihods. hese
methods Cre as wel|
methods Can access columnname.
column index.
data from database
# Cases wbile PetchinaRecord
Case Ii Single
Case T :Mutiple Record
5It doesn't matter how
reconde
aere e Lave to ese loop only
4he Cales
’I oil be used

) Load or Regiater Daiver i


We Can exeeuke tais ste) in two waY
Load Driver
Class. forcName(" ong. postqvesql. Drirer" 3
>class fs present in pactage
puble etate methdd which takes
Eally qualfied path hame of Dâser claus.
partialan clase
lond hat partiudan class into memory
clast NoLFound Excepbian, to hondl
Hhis eeptiom we
handling mechanism.
Way 21
Begiuter Diver.
nen Drirer );
Driver diver
Jivecag agister Driverldriver
hare methoo named
reaister
register Diver,e
Driver() tatesdrier
io DriverManaqer heloer
arumet present
of Drier clast
tokes object gefrence
argument
DrierMauager is not specific for any
’ Specilt database.
part oDRC APT
’DiverManger

classe 4 interfaces related to JDR


Note AU
API are pesent in java. sql package.
DrieeMaraaer pesent injava.sql package
’ Inittaly n IDEC API, prouiions to load
the diver previdad,Driver'"
Cas. ForameC"
ong-postareagl
But here. we have to rememher emamber
of Dïrer
Rully
dass0
Qualifed path name
-lTEl

wio 2
2 Driver diver
DirerMa naqer. egis ler Driver( Jriver)i
This is More gener alited way a we

bare to nber -Eully


emmber
fall qualitied poth name

ofier class.
We Can have mulliple clapencies io pamexmly
omdatabale. We can cannect Java
depending
praga witmudkinle databases
9cees pariculat Drver

Establish lonnection
thee ting
way ii Create onnection
arauments
DriverMavager.qetlonnection(Gting ul, Strirg er
shig
i postqresg!:/ocalhost:s432 /db-Mame
JJbc whichever datbase we an
fay that databaje
wl (wniversal resource lo coteusin
we fare going to have speciic
er name
pauswod( posswod of database)
qetlonneetion) throms sqlExceptiom, T s checked
Exception port namber 3306
has
mysq
get Conneotion () eturns o nnection object.
what is Cannechion 2
Connection gn Interface
Connectin present loside fava. sql packaae
DATE

Note & There are man Connection available


from dfferent Pokagei. Make sur
paikagei
nportiag Arom ja.a| packag
way2
Connection. singk Shing agurat
get by pausing.
pasing
qetConne&tion( Strde wr)
-) rl user
Postgres paswond root
Suhmit esername
-).
have to
After '9'we oue Submit
pastond inakey
în kl valu
value poir
paHern
-) Al websites use game usernamekpaiswond pasi
ELpase ulaserz

qetcomnectim ()

-> (npate a Pile en


n maven. praject by right clicki
maven praject l nà
name

Abconlig-propertier
Caoeate VnitetnptStrzam fteINpukshream
-) FileloputShram
fileInpatStheam Alelnput Stream ntw
Create

EileInputStream
a ictass 9n Java which s wie to rad
dato fem a Pile.

Propeeties
It s a clase io Java hat epesents set ot
prnpertiesof ten uied fox cnfigurakion settin
+Tiransition rom stotement' to 'PreporedStatemsek

»PreparadStatt ment obËects are pre-Curmpiled en data


base seryer, which means that the se statement
Rc parsed and aptimised once
’ This Can resudt in ingroved perfrman
especially tar sq quenien Ahat are executed
mulkiple Eime with ifferent parameter
The dakabase secver Can meuee he
Pxecutiom plan for pre-compiled statement,
educing'ovenbead
w)Readabiliky k Maintainability
> PrepareStodement ' querie an generally m
eadable & mciotainable than cmcanitad
SQL queries
> SQL code is cepareutd from_java code making
it easfer to understand and moify ck of
educes the
’ This separation alea fo the SoL
introduciaq syntax ercor

#Create ' Statement!eaing 'Prtpared Statement' :


) Write (Query calng ith delineter
IUSER] INTO Student VALUEs2
-Sring Quny
Shing Quuny in preparedStatement
PrzparedStatement pstm
("shing quary")}
DATE

data to be
s)Use 'pstm' objeck
ahject to set ar to
setomethods
feed
storedUsing Cindexlcal-name, Yalue
Ptm. set Datatype
4) Execute pstm
> pstm. execute CO
eparedlstotenunt 9(6-call-stored
towe 0eed
do PrOcedre)
To execuke' dlynamic qwenerfit we naed
eKecute clynamic quories,
it's 'Delimeters'
to wite Que alons with
dalimeter
hr erery fietd,be uil have e
> We hasemutigle sete) methods deendig
datastm
> Execute
bypewlich holds key vale
cute
# exeeute
8totement:
DRG providet 3moinoehoda fox executing
sal statement each servinga Aereutppot
metlod. Thia mek,
query using lexecutes)
Oexecute
versalie and Can be esed
statement.
boolean value that ini cates
O,IE eburn fetched cr not.
un be
hether Result Set Can object can be
ResutSèE
CReturns rue
fetched, eturns folse if there is no

can be used or exeutin


) execube c)method
VPDATE DELETE, TNS ERb
SELEC T

methodi used to retieve


qetResult Set )obiect. that contains the data
ResultSet It i ty pical
sq SELECT
etrtved froro sgl SeLEn usin
allad aftermehedefecuting sq!
ezecute ) on statemakt object.
This mehed can throw sglexceplion if Hhe
wa istue witth he dababae connect
if thene ir ResultSek associated
ith statement

Execuk Query waing lexecute Upolate Co


Tuis netadd
S¡l statemants ttaa
pecttteally
data
databaje, sueh ae INSER UPDATE, DELETE
statement.
DATE

IT
t f oot
meant for executing sql ELECT
qurie, nlichinetieves data fromdatubase.
It retum Tnteger repncsenting the mumbr ok
afecked
Alote If we by to Me
wie ezecuteUpdate ()0 mehod
fos SELECT quegit
uetit thnows sgl exception
wita an errór eASage indicotins 4hat
hie mehod appzopiale Ear
Thit because executelpdate () retuns
number ofows affeoted by the
statermenk, which does not make any
Sente fr sELECT bype query ad it
daes not Modiky

Namel
Return boalean int Resultset
(tru ResultseB Fetch) (no. of modified rowg) (interfo
fadse Restsek
Creatt

Read
X

Update
Delete X
need to wse
To Fetch olata/value from cord we sQLEKCEPITION qety tho
getInt (int column Index) thmows
Rarameter e aguments ( column indax ¢otmn heim)
Cal indey not tabue era.
id
e ! rturn! col vat
retumimttl
+| How Resultset Works EXCEPTIGN
created o table, in whih we
Suppose have ta ftoh
I want
have multiple records and we ELECT
these rec¡nds totoc
happen, we necd
)We wil "erecute(ery
Resull set
e
retuen fram dakabae
return
halding data
)l Reswtset i halding a CuO.
V)
v he cuts
Taitally his wwon'tt be pointing towand
any recordi
to fetch cod so, we
I nan
method.
poinking towade ang re coxd1
starts
starts poanion,
pion,wn when we try to
kteh data ustng qet c)method
# Batch Execubion

Batoh Executtorn

bucket

Java Appicahog Dotabae

Batch exec ution JORC valuahle


a

topit, siqnificanth, impreve the


of datoSase operatons by geducin
round ips Prom' Tava kpplbahion to
database
Batch executiom allowp onuliple spL statemnis
to be sent to datobase
Can resull in improved peronaebatch
fes operotion that iovalve malliple ingerts,
updates,a deletes

Beneft of Batch Executian exeuto


)Atomicity i The entire bateh a
unit

fails the entine batch &


IP onL - statement
olled back, ensuring data consitteng
) Redued Network Overhead &
Batch executicm meduces network traffic
wlhich can be signiticant kor performance
Postasesl does not cznplekely supperts erecukins
multplé stakements witain batch when o
Aney produce varging update count
VALUES (1, 'Ka<a'):
statement. addßatch (INsERT INTO Student
INSERT ND student VALDES (2, 'Saurabh');
statemernh add Batch("INSERT INTO student vAUES (3,'eval'):

throws Batch UpdokExcapHen


results were, metuned)
(Too many undte
int [Tex ecut eßahch = statement.e gecute Batch ():

You might also like