Académique Documents
Professionnel Documents
Culture Documents
AllArticles
BestPractices
EnterpriseJavaBeans
JavaandXML
JavaDataObjects
JavaEE(Enterprise)
JavaIDETools
JavaMedia
JavaSE(Standard)
JavaSecurity
JavaSysAdmin
JDO/JDBC/SQLJ
JSPandServlets
OpenSourceJava
P2PJava
WebServices
WirelessJava
RecommendedforYou
StoredProceduresforJavaProgrammers
Print
SubscribetoONJava
SubscribetoNewsletters
byNicFerrier
08/13/2003
ShareThis
ThisarticleexplainshowtouseDBMSstoredprocedures.Iexplainthebasicsandsomeadvancedfeatures
suchasreturningResultSets.ThearticlepresumesyouarefairlyfamiliarwithDBMSsandwithJDBC.It
alsoassumesyou'refairlycomfortablereadingcodeinaforeignlanguage(thatis,notJava),butdoesnot
expectanypreviousstoredprocedureexperience.
Astoredprocedureisaprogramthatiskeptandexecutedwithinadatabaseserver.Youcalltheprocedure
fromaJavaclassusingaspecialsyntax.Whenyoucallit,thenameoftheprocedureandtheparameters
youspecifyaresentovertheJDBCconnectiontotheDBMS,whichexecutestheprocedureandreturnsthe
results(ifany)backovertheconnection.
WebScrapingwith
Python
Print:$31.99
Ebook:$27.99
UsingstoredprocedureshasalotofthesameadvantagesasusingapplicationserversbasedonEJBsor
CORBA.ThedifferenceisthatstoredprocedurescomefreewithlotsofpopularDBMSs,whileapplication
serversaremostlyexpensive.Thisisn'tjustanissueoflicensecost.Thetimeittakestoadministerandwrite
codeforappservers,andtheincreasedcomplexityoftheclientapplicationsthatrelyonthem,canbealmost
whollyreplacedbyarelianceonyourDBMS.
YoucanwriteyourstoredproceduresinJava,Python,Perl,orC,buttheyaremostoftenwrittenina
languagespecifictotheDBMSyou'reusing.OracleusesPL/SQL,PostgreSQLusespl/pgsql,andDB2
usesProceduralSQL.Theselanguagesareallverysimilar.Portingbetweenthemisnomoredifficultthan
portingSessionBeansbetweenversionsofSun'sEJBspec.Inaddition,storedprocedurelanguagesare
designedforembeddingSQL,whichmakesthemmuchbetterforexpressingthedatabasemechanicsthan
languageslikeJavaorC.
JustEnoughMath
Video:$129.99
BecausestoredproceduresrunintheDBMSitself,theycanhelptoreducelatencyinapplications.Rather
thanexecutingfourorfiveSQLstatementsinyourJavacode,youjustexecuteonestoredprocedurethat
doestheoperationsforyouontheserverside.Reducingthenumberofnetworktripsalonecanhavea
dramaticeffectonperformance.
CSSSecrets
UsingStoredProcedures
PlainoldJDBCsupportscallingstoredprocedureswiththeCallableStatementclass.Thatclassisactually
asubclassofPreparedStatement.Imaginethatwehaveadatabaseofpoets.Thedatabasehasastored
proceduretosetapoet'sageatdeath.Here'sanexampleofcallingthatstoredprocedurewithdetailsabout
theoldsoakDylanThomas:
try
{
intage=39;
StringpoetName="dylanthomas";
CallableStatementproc=
connection.prepareCall("{callset_death_age(?,?)}");
proc.setString(1,poetName);
proc.setInt(2,age);
cs.execute();
}
catch(SQLExceptione)
{
//....
}
ThestringpassedtotheprepareCallmethodistheprocedurecall
specification.Itspecifiesthenameoftheproceduretocallanda?
foreachparameteryouneedtospecify.
RelatedReading
IntegrationwithJDBCisabigadvantageforstoredprocedures:in
ordertocallaprocedurefromyourapplication,youneednostub
classesorconfigfiles,andnothingexcepttheJDBCdriverforyour
DBMS.
Whenthiscodeisexecuted,thedatabaseprocedureiscalled.We
don'tgetaresultbecausetheproceduredoesn'treturnone.
Successorfailurecanbesignalledwithexceptions.Failurecan
meanafailurewhencallingtheprocedure(suchasoneofthe
argumentsbeingspecifiedwiththewrongtype),oranapplication
failure(suchasthrowinganexceptiontoindicatethat"Dylan
Thomas"doesn'texistinthedatabaseofpoets).
CombiningSQLOperationswithProcedures
MappingJavaobjectstorowsinSQLtablesissimpleenough,butit
usuallyinvolvesexecutingseveralSQLstatementsmaybea
SELECTtofindarowIDfollowedbyanINSERTofthedatawiththe
specifiedrowID.Inahighlynormalizedschema,theremightbe
multipletablestoupdate,andthereforemanymorestatements.The
Javacodecanquicklygetbloatedandthenetworkoverheadfor
eachstatementsoonaddsup.
JDBCPocketReference
MovingallofthoseSQLstatementsintoastoredproceduremakes
ByDonaldBales
lifemuchsimplerandinvolvesonlyonenetworkcall.Allofthe
associatedSQLoperationscantakeplaceinsideofthedatabase.
Inaddition,storedprocedurelanguagessuchasPL/SQLallowyoutospeakSQLmuchmorenaturallythan
ispossibleinJava.Here'sourearlierstoredprocedurewrittenusingOracle'sPL/SQLlanguage:
createprocedureset_death_age(poetVARCHAR2,poet_ageNUMBER)
TaggedArticles
Bethefirsttopostthis
articletodel.icio.us
poet_idNUMBER;
begin
SELECTidINTOpoet_idFROMpoetsWHEREname=poet;
INSERTINTOdeaths(mort_id,age)VALUES(poet_id,poet_age);
endset_death_age;
Unusualimplementation,no?IbetyouexpectedtoseeanUPDATEonthepoetstable?Thisisanindication
ofhoweasyitistoimplementthingswhenyouusestoredprocedures.set_death_ageisalmostcertainly
badlyimplemented.Weshouldprobablyjusthaveacolumnonthepoetstable.Itdoesn'tmattertotheJava
codewhatthedatabaseschemaimplementationis,becauseourJavacodejustcallstheprocedure.Wecan
changetheschemaandtheprocedurelatertoimproveperformance,butwewon'thavetochangeourJava
code.
Here'saJavamethodtocalltheaboveprocedure:
publicstaticvoidsetDeathAge(PoetdyingBard,intage)
throwsSQLException
{
Connectioncon=null;
CallableStatementproc=null;
try
{
con=connectionPool.getConnection();
proc=con.prepareCall("{callset_death_age(?,?)}");
proc.setString(1,dyingBard.getName());
proc.setInt(2,age);
proc.execute();
}
finally
{
try
{
proc.close();
}
catch(SQLExceptione){}
con.close();
}
}
Usingstaticmethodslikethisisagoodwaytoensuremaintainability.Italsomakesthecodethatcalls
storedproceduresintosimpleboilerplatecode.Ifyou'reusingalotofstoredprocedures,you'llfindyourself
justusingcutandpastetocreatemethods.Becauseoftheformulaicnatureofthecode,it'salsopossibleto
scripttheproductionofcodetocallstoredprocedures.
Pages:1,2
NextPage
2015,OReillyMedia,Inc.
(707)8277019 (800)8898969
AboutO'Reilly
Community
PartnerSites
ShopO'Reilly
SignIn
Authors
makezine.com
CustomerService
Alltrademarksandregisteredtrademarks
appearingonoreilly.comaretheproperty
oftheirrespectiveowners.
AcademicSolutions
Jobs
Community&FeaturedUsers
Forums
makerfaire.com
craftzine.com
ContactUs
ShippingInformation
Contacts
CorporateInformation
Membership
Newsletters
igniteshow.com
PayPalDeveloperZone
Ordering&Payment
TheO'ReillyGuarantee
PressRoom
PrivacyPolicy
O'ReillyAnswers
RSSFeeds
O'ReillyInsightsonForbes.com
TermsofService
WritingforO'Reilly
UserGroups