You are on page 1of 50
Ispiders Author:-Shishira Bhat Training & Development Center Technical Architect JDBC When the method yeturntype is superclass then hat method can return Supexclass object . when the Method parameter fs of superclass , then he argument must be A Subclass object: TARR Files? > Jar file means a java archive file ie it's a compressed folder which contains java and nelakd files. > Generally the jay file contains .class files and othex configuration files. % xm and «properties sre general configuration fies. Tava Archives t > Generally we dont share java files in jar file. 7 Command 1 creat a jar is given below jar . compressed ver br Adding libraries fate the project CButld Pat) > dt is always a good practice +o copy the libravies int ime project. Steps te be followed : 1 Right eléck on the project -> sect properties 2 Sect java build path > Select libraries tab 3. Cleck on ada jays 4 Browse the jar file ~ click on ok + Sf ine member of the jar file ts public, then only we can access ahem. > Before accessing members of jay file we need to import ‘the class. all 3000+ Mbuilt classes of java ave present in Yéjay with appropriak package structere SHISHIRA BHAT Technical Architect www.jspiders.com www.jspiders.com Author:-Shishira Bhat Technical Architect Ispiders Training & Development Center Class Loading * + When any of he member of ‘the class fs called, then thal classis loadea by class loader. + Bringing the class into Jvm memory from the hardkisk can be considend as cless loading © Members of class ave a. methods 6. variables c. constructors d. Blocks # ° Ob is possible fo loat a class without calling any Of its members. SHISHIRA BHAT ‘Technical Architect www.jspiders.com method ote calc forName prName method present in java-lang: Class Syntax of the method is public static class forName CString fallyQualified className ) ; + The forName method throws a checked exception called Class Not Foundé xception. * By using a sta Prognams ¢ package com. jspiders. demoapp public class Load Test f public static void main ( String LI args) t ty ‘i Class -forName C” com jspidets. demoapp. Fish“); 4 catch ( Class NotFound Exception e) é @. printStack Trace ©; System-out. printin 6" Class nat leaded") £ J 7 www.jspiders.com Author:-Shishira Bhat Technical Architect Ispiders Training & Development Center jackage com. jspiders. hemo Fray eh r state £ a SHISHIRA BHAT ‘ Technical Architect ‘ www.jspiders.com olp :- Im loaded Static Glocks 4 A static block is ‘me one which has Some logic as like any other method * Static block is executic Only ot once when a class is loaded. % Static blocks ave exewutd with high priority ie static block ts execuka before y other member. the executio, no. of static blocks & in this case, execution of blocks are + When we have any sequential a * Static blocks ca: % Static blocks 2 class is loa ot be inheriid. ot be calcd explicitly tdeed they ave caled by JVM when Jobe Configurations 2 > All ToOBC configunations data must be glebal constant. > AU examples ef TOBC constants 41. DB username 2. DGB passwora 3 DB ORL Besign Princeples ? "Program an tatexface, but not an implementation ” Ex! List Ist? mew ArrayList)! Ist. adel C"shishiva” ): Ex: Switch sw> new LedlightSmpl C); Sw. switchOnc,; Sw switchOc); > The subclass of an interface fs calad as implementation class. > The object Of subclass or fmplementation class is calad as Implementakon object www.jspiders.com Ispiders Author:-Shishira Bhat Training & Development Center Technical Architect Advantages of interfaces > 1 Loose coupling 2. Abstraction. Factory Design Pattern : Program. :- package org. jepidets . demoapp; public interface Switch # Void switchOn C); Void suitchOf cd! ‘S.com package org jspidexs. demoapp; ce Implementation class =7 public class LectlightImp! implements ISwitch @overrida public voit switchont> S-apl" LEO light switched on"); @ovenvide public void switchoffc> S.o-p (LED light switched off"; 3 i W writ. SolarlightImpl & Metcurylightimpl classes same as Ledlightmpl package org jspidexs . demoapp ; public class Light Factory f /® Helper method or factory metod * @autnor Shishira Bhat * @param type of Light * Helper memoa ~/ pubic static [Switch getlight (Strieg typeOflignht ) ¢ Of CtypeOflight equals ("ka") ) www.jspiders.com IJspiders Training & Development Center f vetuin new LeclightI mpi); £ else if © bypedflight. equals C” solar"); Gi Author:-Shishira Bhat Technical Architect, vetwta new SolarLightImp! ©); = SHISHIRA BHAT Te retunn new MercurylightImp! (): onan ar ; if 5 3 3 package org. jspiders .demoepp; import javavettl. Scannex; pubuec class Test Public static void mainCStringlI args) Cs Usex users new User )' user. veaaly Package org. jepicers . demoapp; Imporé java-util. Scanner; pubue class Usex é public voit veaa 6) e Scannex scan > new Stannex C System.in): Sop l" Eater light of your choice"); Sting typeOflight = scan. nextc): TSwitch sw LightFactory. getlight ( typeaftight J: Sta SwitchOnld; sto. switch Off) www.jspiders.com Author:-Shishira Bhat Jspiders Training & Development Center Technical Architect Oulput > Enter light of youn choice lea LED light Switched on. LED light switched off Object Constants and Global Constants > Object constants are The constants which ave applicable for an object. where as glebal constant ia is the one which is applicable for the entire application. 7 Ex! public final String carmover = “alto” ; /object constant public static final doubu PIE 3.1¥2; 1 global constant > Object constant has one copy for one object. [instance] + Gk isa good practice te define the global constants in an interface. because all the data members in an interface ave public static final > t's again a good practice “that final data members must be in uppercase. i > Data members of an interface can be accessed by using interface Name. because it i Program $ : package org jspid gee intexface A String user. wame= “scott”; String PASS= * tiger”; double PIE 3.149; int AGE = Ic; 3 package org. jspiders .demoapp; public class Dovsex 2 public static void main( Sting! ] args) f S.e-p U AppConstants. useename ); SHISHIRA BHAT S.o-p ( AppConstaats. Pass): Technical Architect 3 www.jspiders.com £ output j- scott tiger www.jspiders.com Ispiders Author:-Shishira Bhat ‘Tr ing & Development Center ‘Technical Architect State mport : > Static import is a feature of java which is introduced in jdkI-S > This feature fmports all static members either from an interface or abstract class ov a class > OF we use static Fmport then the static members can be accessed without using ‘he classname or intexface name. Program 4: package org.jspidens. demoapp; import static ong. jspidets.cemoapp. AppConstants. *; public class DbUsey t public state void main (Stringl] args) SHISHIRA BHAT Technical Architect www. jspiders.com Sovp Crass); S.o-p C USERNAME): i 5 Costly Resounces Heavy Weight Object : > Generally most 9 logical objects ave lightweight objects. ie once an object is cveaid in 4 ap memory ,it may not use the system resounces hence once the object is deveferea , the logical object which 73 present fo heap memory ts destroyed. ? Sometimes when we creat ‘the logical objects , they Start using the system resources anc when the logical object is devefered , logical objects ave garbage collecka but System vesounces are not released. > When we have Such more and more objects which uses system resounces the Application performance is reduced. Hence it is very important to close such costly resources and release the sysum resounce. > Costly resounces canbe closed using the close method [ ctoseC)] > We generally close the costly vesounces fnside the finally bleck Ex: Streams, OataBase Connection ete. FiteWriten = new FileWriter C“data-txt*): System mae ‘de-vefered idata-ixt| = new Filewritex C“emails.txt “); SH Resour FileWriben finally t fw closet); b www.jspiders.com — "esp emery Ispiders Author:-Shishira Bhat Training & Development Center Technical Architect Apptication Programming Sntexface * FAPL is a collactop of interfaces, helpex classes and implementation classes which is used for inten application communication in a leesely couphd way. > OF java based API then it is generally given ia the form jar file. > APL is the physical form Of abstraction > APl's are generally given by application providers > There are many categories of API's. E wv L 13 z : oe m 9 He E He 2 P t ? : SHISHIRA BHAT Technical Architect = 3 www.jspiders.com Tt) 0 Helper Class iP Le APL. jay Smpl- jar JoBC > Onivens > % Daven is the piece of code of set of instruchions which helps f communicate between % aiffevent nfw systems, blw and a Software and blw multiple software. % A driver can be written in any of the programming language Wke C, C++, java ete. * Dover works like 2 tvanslator- Exampis : Printer Dover, Camera Dotver etc. + the dhivers which helps f communica with the devices are Calud as device dnivers. JDBC Daivers > % JDK drvenisa piece of code which helps t communicak from a java program or application with a database sexuer. > ZoBC driven works asa translator bl java application art DB- Server > Tose driver transiaks TOBC instructions (JDBC catis) inte native database instructions C native DG Calls). > There are auffrent types of TpGc drives called types , typea, types, type + www.jspiders.com drivers Author:-Shishira Bhat Ispiders ‘Technical Architect Training & Development Center > Type4 divers are written in java language. TDBC Archifctune > [roe | Tava A Program p or I application 06- Sewex Ex> #MS~- SQL Senuen SHISHIRA BHAT ¥ 1am 0B Technical Architect * Denby www.jspiders.com * Onacl ¥ MySQL * Sybase “7 We have te writ. java application or progyam by using TOGC API > JoBe Api 7. +o achieve loose-coupling ble java application and database Seusers When we make Tose calls which are transla&d to native DB calls by TOBC duivers. Hence from java application to communica with any 0B -Sexvex we have fo “se API as well as Dxiver. > Conclusion: *Paxpose of API 7s laose- coupling. + Punpose of Oxiver is translation. Sowers : + A sewer 7s a sw which Serves the cleat request % Server does not creat any resources on its own. Indeed it Serves only if the resounces ave Available. % Different types of server 1. DB Sexver 2. Web Sewer 3. Appiccation Seren. % Example for DB Sexwex is oracle, sybase, My- SQL. * Example for web Sexwex Apache and Temat, jetty, Sun, GlassFish »* Example for app Sewer is TBoss, weblogic, WebSphere, Dynamo. www.jspiders.com IJspiders Author:-Shishira Bhat Training & Development Center Technical Architect DB ~ Client :- > DB - Client ts a lightweight or thin client Applecation using which we can communicat te local or remolz senver. > Example Toaa, Squirrel or squ-yog for Mysqe , S9L Work Beach > The fnformation which (s required fp access the remotly hoska senwex ts calud as host faformation > Below are the host fnformation IP addness of the Server COB) SHISHIRA BHAT a b+ Port Number Technical Architect ec. Usex Name www. jspiders.com a. Password Installation of MyS@L ana SHLYog Softwares + Doub click on -exe file > cuuck Yes > click en compli -» Next > skip signup > click on next> check te option "configure mysql sever” > click on Finish > “instau as next> select standanct configuration “> next » check the option check “Launch MySPL sewer automatically” > check "Sncluda ows path” > next > enter Toot password And confirm > check bin directory fa wi enable rook ace. next > next> Finish. S9L- Yog + Double cli xb? licence agreement ~ynext> next> Finish Connection bame -> OK -> localhost > click on connect [test connection] -7 save changes. Progham® package org. jspidexs . app; /* import classes from jay file #/ Import com. shishira « pdfapp -POFGenerator; Import com. shishira ~pdfapp- POFHelper, a class PoFuse public static void main C String lI args) t Sop (" App start 74 get hidden Implementation object fiom helper factory #/ POFGenevator pdfgty = POFHelper. gen POF C); /* abstraction */ pafgty: genevakPDF C2; oe * App ena “I; www.jspiders.com Author:-Shishira Bhat Ispiders ‘Technical Architect Training & Development Center Properties = > Properties is a type of cata which stores the data ia the form of key-value pair. > Properties file is platform aad technology independant. % To read the data from a properties file, we have to use the + javaio. FileReaden; java- Util. properties ; 7 While reading ‘the data from properties file we get checked exceptions 4 java.io. FileNot Foundéxception. 4 java.io. Loexception. > FileReaden fs a castly yesounce hence it must be closea Tdeally fnsiae the finally block. + To neaa the dala we use 2 overloaded methods of java. util. properties Cless. 4. public String getProperty CString key) > The method takes key as.an argument > Of the key7s present then the memod returns me assouakd value. > OF th not present, then ft returns nail, but we dont get any exception 2. public String > The mein > of error Property ( String key , String message) retwins the assouaka value if the key fs present 15 not present the message could be returned. Programé : package org. jspiders. app ; Import java.io. * ; import java.util. properties » pubbe class Property Readex - publec static voicl main C Stingl] args) SHISHIRA BHAT t Technical Architect www. jspiders.com Properties props> new Properties C); FileReadee readex = null; try f reader = new FileReader ("config !dbconfrg. properties"): //FiteNot Found exception, prps.loaa Conader)) // IOException. 7# Readl get the property */ String oraclkUsen > props .getProperty ( " ousex String orackPass> props. getProperty (” pass”: Sop ( ovack User +" "+ ovaclPass J; Striag mysqiUser> props: getProperty (“usr 9 “Key not found"); S:0-p C mysqiUser); 5 catch (Exception €) £ € printStack Trace; www.jspiders.com Ispiders Author:-Shishira Bhat ‘Training & Development Center Technical Architect finally E try 7# close costly resounces */ reader. close); 3 catch CE IOException ©) 7 2 ie SHisitikA bHAd e@.priatStack Trace C); Technical Architect ; ¢ www. jspiders.com i Output : seott tiger key not Foun: JDBC APL: > zD8C APL contal classes C Hel > All these + java-sqi + javaz. sql. > the basic ftatunes Of TBC are given fa the form of API which Ts present fa many fntexfaces, many fmplementatrons classes and helpex 1 Factory Emplementatvons ] are modularizect into 8 package Java-sql. package. > The extended feature of JDBC which ave in the form of API ave present Javex.sqi package. Note TOBE members are the part of TRE Iibrary- Hence they need not to be added fo the pryject buildpath * The Jowe API is given by the sun microsystems. P APL's ave exposed to two categories of users Category : Developers or programmers who use the intexfaces or helper classes ofan API (usage logic ) Category 2: For Emplementation jrovider je the one who gives an implementation €0B- vendors) TDBC- Datwers PIDBC driver \s an implementation of JBC API. > ypBC API daivers whch conta'ns implementation is given by DG- providers www.jspiders.com Author:-Shishira Bhat Ispiders Technical Architect Training & Development Center who ave typically caled as O0G-Yendors. > he TDBC Daiverés vendor speafic ie it is DataBase specific. > The dnivet given by MySQL can be used te connect with MySQL OB sewer and cannet be used fo connect with some olher DB Server. T0BC dnivets ave given fn the form of jar files . Hence this drivetjar file has to be added fe project buildpath. eee pans JDBC vendors 5 ° Orack a ay a — ay t P L Jpec API t omacl Sever e % He acum m my-sq| 9 y Daves |” s P 9 My-S@e Sewer | L ‘ SHISHIRA BHAT j Technical Architect | www.jspiders.com ievenanind ig ia : 2 mpl Dea Seaver Daiver Jan Files :- 7 mysql - connector - version. jay Ex: mysql- connector - 3.1-jar # ojabe version. jar Ex! ofdbe tea. jar www.jspiders.com Ispiders Training & Development Center Author:-Shishira Bhat Technical Architect 1 ° r0g /cteveloper mpl provider iz ao ee | ort iG eee | som.ge( ~~) Vv {etaes Clmer FE] |e] argument: ; WWovewvide se - ‘ 1.) $ -stmpler-? Smplementatialsub obj uc} Dm (ey 3 ‘ es6)¥ ey oo pubice statte C ge Co-)/ em ‘ ivef-el ©); 7 pron |p ‘ } usage-logic 4 ‘ ofelbelujay ' returns i . Hidden Ompt _-” ipl obj ToBc- Ari + aa peas : MySOC Driver 5 Smpi roysqu jay Daiver Classes :- * Onade: onada. jabe driver. Onacl Driver * mMysge com. mysqt. jdbe . Driver Microsoft (MS~ S94): com. microsoft» sqisexwer. jlb¢ -SoLSexverDriven JDBC ~ Specfications £ Java-sqi <=> Dxtiven HC | package jave-sqi |) puvice ciass Dxwermanager £ Public static wid registerDaiver (Driver 4) www.jspiders.com SHISHIRA BHAT Technical Architect www.jspiders.com Ispiders Author:-Shishira Bhat ‘Training & Development Center Technical Architect ackage ovace jabe. duteer en en A 5 specifications x @ public class O7aceDaicer ? java-sqi.Dateor if static | > speafication2 ft OnaceDatvee od = new OnaceOntoer ); DateexManager - nagtstetDateex Coa); 7 >RO me > Specifications a } SHISHIRA BHAT Technical Architect www.jspiders.com Spesifcstions : > The diver class pan i otioay ven by DB Vendors must Implement an fatexface cated ich is the part of JOBC Apt > Alu the diver class provided by OB Vendor must have static block 7 Inside the c Block daiven object must be creatia CSame class object ) > Created Aniver object must be Fagisteved with 3 static method calad “yegistexDriver” which fs present in java-sq!.DniverManager which fs the part of To8C api. > Below 7s the syntax of the method publtc static void vegtstexDniver Cjava-sql.Dniver on) TowBe Definition + JO6C is the specification given fa the form of abstractioa API +> communicak with OB Sewer i an independant cay: Advantages > 1. loose coupling ble DB Sexvex and java appiccation 2. Flexibility 40 connect 1 arffrent DB ie DGB Independant. 3. Platform independant. JDBC Dnfyex Classes :- class com.mysql-jabe Driver implements java. q!-Onivex class omacl. jdbc - driver + OnaceDriver Implements java sql.Datver class com. microsoft. sqlsewex.jAbc . SqlSexvexOnivex Smplements java.sql. Oriver www.jspiders.com Jspiders Author:-Shishira Bhat Training & Development Center Technical Architect (To communica from 3 java program with any DB Sever we need an object of Oniver class - > This Oniver classes ave provided by database vendors like ovack, mysq!, 062 etc fr the form of jax file Pk is Very important to creak an object Of Me Aniver class Creating an object Of Diver Class > > java.sq!. Oiver interface has an abstract method. > Syntax of method Is nect CString urt , Properties props) Throws SQLException user = rook password =dinga Technical Architect www.jspiders.com «properties > Connect) method fs implemented. in the Onivex classes which are given by DB Vendors. > The _connectt) returns the connection object . 4. jave.sqi. Driver d = new Onacl jdbe.driver .OnackOziver€)' © Connection con = cd. connect (~~~ )5 wacle jdbc. drtiver. OrackDvirer’) - newLnstance C)- 2. java.sq/. Driver d= Cjava.sql- Driver) Class.forName C’ Connection con= d. connect (.~,.~); Onacle Server Java www.jspiders.com MySGL Server Ispiders Author:-Shishira Bhat ‘Training & Development Center ‘Technical Architect << interface >> java. sql. Driver public Connection “connect (Sb properties fafo )) [—» part of ToBC- API uRL, |» given by sue 9 given by ovacle. jolbe. cbrivet. Onack Driver mysql . tbc. Driver | @ ovenrice @overrids pubtce Connection connect (x, v) public Connection connect C47) t t yetuxn My-S@L Connection Lobject J J a } return omacle- os given by 08 Vendors part of JDBC Driver 7 To establish the connection with DB Server we neec connect method. > Connect method is given fn Driver fatesface by Sua Microsystems and logic is given by D@Vendors ia the Driven Class (Method ts overvidcden) > To calt the connect) method we need object of Driven class . URL CUntfrm Resounce Locator): > URL ts the path which is used to Sdentify ‘the resources over the network The syntax of JOBC URL is SHISHIRA BHAT Technical Architect www.jspiders.com main protocol: sub protocol : Resource Path mysq! } fabe: mysql! @ locathost / 3306 ——————Plecathost- sewer jbo? mysqli 7 192-160 .a4-5C : 3306 ———> Remok. host Onacle { jdbc: ovacl: thin : / localhost : 1621 ———— localhost Sewer | jdbc: ovack : thin t 7 192.160. 46-1 2 1S8l ——> Remok host > The connecttda method throws S@LEXEplion If the given URL is wrong > @ can be used Mashacdtof ‘7 fa the URL www.jspiders.com Author:-Shishira Bhat Technical Architect Ispiders Training & Development Center Not : Gn the URL we may pass the deta also Establishing the Connection with Mys@l Sensex : Sting URL = “Gdbe: mysql: 7 locathost : 3306 "5 Properties props? new Properties); FiieReaden fr * new FileReaden (" mysqidbconfig + propertres” J; % FileNotFound Exception props-load (fr) ; // LOE xception 1% approach : java. sql. Driver A= new com.mysql:jabe » Driver C1; java. sql-Connection con= a. connect Curl, props) ; %S9L Exception 2" approach: Java sql. Driven a= Cjava.sqt- Driver ) Class. forNiame C" com.mysq|.jdbe: Driver ww, + newOastanceC); Hinstamtiaton€xception Java-5ql.Ewnnection con® dh. connect Curt, props) ; / S@LException user=root | password. = dinga mysqidb config. properties Geking up the project tn Eclipse > > Creak anew java project im eclipse ? Creat appropriak package structure under src > Creal a lib folder and copy asiver jar file > Add the jar file fnto project build path » Creal me properties file under config folder Coptional stp] Divectory Structure! ibin T10%9"| on] oo Properties fb i Z bora | SHISHIRA BHAT Technical Architect www.jspiders.com rae Hee] 1ysqt driver jav 10 Ispiders Author:-Shishira Bhat Training & Development Center Technical Architect Program 1: package org. shishira. abapp; fnport java.io. FileNot Found xception, Import java.io. FileReacer; import java.io. Loéxception: import “java.$ ql. Connection; import “java.sql. Daiver ; import “java.sq!. SPLExeeption; import java-ukl. Properties ; public class MySqiConDemo t pubite static void main( String lL] args) 2 final String URL =" fdbe: mysql: 1 locathost : 3306 final String Diver =“ com.mysq! jdbc. Daiver ”; Properties pro FileReadex read ory z veadex = Reader C” config /mysqidbconfig . properties”), Props lo: ten 2 Daiver d > new com.mysqi-jdbc- Driver C2; Connection con= ad. connect ( URL, props): Sop (" Connection suctess"+ con); f catch ( FileNot Found exception €) ft e priatStack Trace C2; J catch (LOException €) i e-priat Stack Trace ()' f catch ( SQLException e) € e-prints tack Trace 2, a finally - if € reader! = null) é yt vea der. close (2° www.jspiders.com SHISHIRA BHAT Technical Architect www. jspiders.com Ispiders Training & Development Center catch CLOException €) r eprint Stack Trace ()" 3 Author:-Shishira Bhat ‘Technical Architect Program @ : Package og. shishi ta . dbapp; Import java.io.# ; Import java-sql-* ; Imporé java. util. Properties ; public class my t public static void f final String UI Abe: mysql: # locathost : 3306”; final Sting Deiver =" com-mysq! -jabe - Driver” ; Properties props new Properives (2: FileReaaer fr = null} try é reader =new FileReader C" config/ mysqidbconfig - properties”), props-load ¢ reader); Driver a = COniver) Class. forName ¢ ORIVER) . newSnstance >; Connection con+ d. connect ¢ URL, props); Sop © Connection suctess - "+ con); a cateh ( FileNotFoundException ©) e eprintStack Trace (2 3 catch C LOException ¢) £ e-printStack Trace (2; a catch CS@lexception e) & e-print StackTrace 2” 3 Deol rain € String lI args) SHISHIRA BHAT Technical Architect www. jspiders.com www.jspiders.com JIspiders Author:-Shishira Bhat Training & Development Center ‘Technical Architect catch ( QnslantiationException €) ft ©. priatStack Trace (2; 5 catch ( ClassNotFound exception ©) fe e-prinkStackTrace (2; A catch ( JlegalAccess Exception e) e €.priat Stack Taace ¢; F, finally a SHISHINA BHAT Technical Architect www.jspiders.com tf C reader! =null) f ee) z e:print Stack Trace ly 5 # 5 3 5 Types of ure! 1. URL with host fafo: jolbe: mysql: # localhost 73306 2. URL with host info 2 Data : jabe. mysql: / locathost ! 3306 ? usen = rook & password = dinga- ToBC Skps> i. load and vegistex the oliver it. Establish the connection Creat Statment 3 types of stakments + staameat + prepaved statement www.jspiders.com Jspiders Author:-Shishira Bhat Training & Development Center ‘Technical Architect + callab statement. iv. Execué the query or sg. statement. v. Optional skp: Process the data vi. Close alt the JDBC Resources. Stpi: Load and register the dhiver : 4 The diver class is given by DG vendor can be loaded and registered with Oxivermanagex by using below 2 ways SHISHIRA BHAT Technical Architect www.jspiders.com Options : Syntax: — Class.fovName C“ Diver”); Ex: Class. forName (“ ovacle.jdbe.dniven . Oracle Daiver " ): Class forName (" com.mysql. jdbc. Driver Class: for Name ( “com. microsoft . sqiserver. SqlSetvet Driver"); > frName(d isa slate metod whichis present java.iang .Class >The forName() metod loads the duver class whichis he part of jabe driver Y This possibly gives a checked exception calluct ClassNotFounde xception. 7 When forName () method loads the given class the static block of Dnivex class fs execukd, whieh has me code to creak its own object and megister that object with DaiverManager using the registerDniverC) memod. 18a Static method which ts present in java.sql. DriverManager > syntax: public static veid vegistexDriven (java.sql. Driver On); Not. > This fs highly prefered way of loading and registering the dniver because developers dont have fe creat me depeadancy eon the O.river class. Option 2: > Creat an object of Daiver class and register explicftly with OriverManager using registexDriver() method. Java.sql- Driver odniver= new oracle. jdbc. driver - Onace Driver C2; Dxiver Manager . registerDriven( odnivet); C for ovack J java.sql. Driver Mdnivet = new com.mysq!.jdbc. Oniver 6)" DaiverManager. vegisterDnivex Cmdaiver), Stp2i Establesh the Connection with DB Sewer. 7 Te establish the connection with DB Sewer we use the public static method of java-sql. DaiverManagen class caluct getConnection C) >The getConnection method retuxns the connection object for Aan appropriak www.jspiders.com 2 Ispiders Author:-Shishira Bhat Training & Development Center ‘Technical Architect database depending on the Joaded driver. getConnection C) isan implementation of factory atesign pattern % getConnection() possibly throws an checked exceptron called S@lException ~> Three overloaded Vvexsions of getConnection ©) method. — Syntax ? a. public static Connection getConnection CString url) b- public ctatic Connection getCoanection( String url , properties info) c. public static Connection getConnection CString Url, String username, String password ) Demo for establishing connection with Mysql DG Server: Program 9 ¢ package com. shishiva. cap ; import java. sql. €; public class ConDemo z Public static void main Stringl] args) i final String URL = “fdbe: mysql: // locathost : 3306 7 user=root & password = dinga" ; dry é Class. foriame (" com. mysql.jabe. Dviver "); S.o:p (“leaded and ‘registeud ~ success ), Connection con = Daiver Manager. getConnection CURL) S:0-p 6" Connection success"); 4 catch C ClassNot Found Exception €) t €. priatStack Trace ©); $.0-pC" Failed to load & vegistex the daiver"); ee catch (SGLEXcEptiog €) e Sop © Connection fated ")? 5 3 Sample program fo fasert a record 1 the database: 1. Class -forName C" Driver"); /ClassNot Found Exception Connection con= DniverManager. getConnection CURL) ; SHISHIRA BHAT Technical Architect www.jspiders.com U sovexception a 3: Statement stmt = con. creakiStatement (); 4+ iat nor’ = stmt. execut pda (" Tasext info gab student values C$ se", ‘mang, 68.3)"; §- stmt. closet); con. close C2; www.jspiders.com Jspiders Author:-Shishira Bhat Training & Development Center ‘Technical Architect Stp3: Creat Statement Statements > Statement is an interface in java-sql. package > Statement fs the part of JOBC API > Implementation of statement fs given by OB Vendor as te part of JDBC Driver > To get the reference of statement, we use a method cated creakStabment C) Which is defined ta Connection iatexface > The syntax of te method ts public Statement createStatement ( > ~ Statement represent the platform or environment for exetution of sq] statements or quevies like DML, ODL , etc. Stp4: Exeution of query and Sgt statements. > To execul SQL statements , we use the execu methods which ts the define at fo Statement ‘nterface. > We have 3 déjferent versions of cxecukl) method rate SENT rchitect > Syntax wicca 1. public bootsan execut € String 9ry) Wijspiders.com 2 public Res exewalt Query ¢ String gry) 3. puble int ukUpdat CString AmlQry) Le @xewk ©) > exe ©) method is used t exeuk any type of S@L statement ie it is a generic method for SGL exeution exeuk 6? memodts generally used for OpL statements. a. execuQuery 6) : > exeukQuery () method fs used fo execuk Sige statement which generally retwins ihe data. Vieif you wank to query the 0B then we can use execakQuery() method > execubQuery() method returns te ResultSet which represents me processed data Cdata returned from database] 3+ exert Update (2; > exewbUpdat () meinod ts used ty exeuk BB DML statements. > The retuxatype of execukUpdat () is an integer value which represents the No.of represe: vecords affeckd in database. Not! We canno- use enecuk@uery(? method for DML statement. Sf we use thenat vantime we gel- SQLException. F Au the executl) memods possibly throws 4 checked exception cata SGLEXception. nt www.jspiders.com 13. Ispiders Author:-Shishira Bhat Training & Development Center Technical Architect Usage of two pavametotized getConnection( ) methoc : Syntax! public static Connection getConnection CString url, Properties Info) Ex final String URL = "jdbc: mysql: / locathost ? 3306 "; Properties props > mew Properties C4 FileReader freader = new FileReadex (" dbiafo. properties props-load freaden)' // LOExcephion 4. Class. forName C "Driver eae ClassNetFoundéxception 2. Ganection con» DniverManager- getConnection CURL, props): W#sqLexception. U FiteNot Found Exception user = rook password » dings SHISHIRA BHAT Technical Architect www. jspiders.com albinfo. properties Nok + he get Connection’? method taternally has the method t reac the properties (username & pas: ) from properties file. Hence in the properties file Keys must Usage of 3 parametentsed getConnection) method : Syntax: public stati Connection getConnection C String url, String username , Striag password) ; mysql: 4 locathost : 3306 " + Ex: final String vel = "jabe finat String USER: "root Final String Pass =“ dinga"; final String ORIVER +" com.mysq!.jdbe. Daivet"; | Class. fpr Name C Driver) 5 & ClassNotFouad Exception 2. Connection cons OniverManager . getCennech on CURL, USER, PASS)» USQLException Updating a recor from DB : Ste Ragen we 9 updakqry > “updat sdb.student set perc=7I.8 where fl> *s4” ” > 1. load & registet the driver. 2 Establish the comectron 4 3+ Creak Statement + fat nore = stmt. exewk update ¢ Upda&Gry)- 5+ close stmt anc connection Deleting Record from Table = Shing dekk@ry= “ deuk from sdb.student where sit www.jspiders.com = ‘sige "> Ispiders Training & Development Center Author:-Shishira Bhat Technical Architect 1 load & vegisten the daiver a: establish the connection 3. creak statement 4+ ink nord = stmt. execuk Updat ¢ elit. Qry ); 5: close stmt and con. Fetching the data fiom Database? String setQry >“ Sekct * from empab. employee where hload & register the driver a establish the connection 9. create Statement 4+ ResultSet ys> stmt. execu Query CselQry); 1s: nent (+ String name® vs-getstring C"enome"): String id= vs. getString C4); doubla sal > vs. getDoubk ("esa") close stmi Pies Fy 6 o. Result Set * varchar numenicai fa + * ein ename sal et Rama | as000.00 ee Shama 6000.00 23 | Bhama | 3000.00 4. compile 2. exewtion 3. Buffer memory / cursor cursor eg [cas Shama | 2G000-00 >ResultSet fs.an intexface which ts present > Implementation for ResultSet ts given by DBVendor as > Resultset represents me processed data fn Java. sql et = fen? ” > SHISHIRA BHAT Technical Architect www.jspiders.com Package. the part of TDBC Daiver 7 Once query 7s fired from TOGC program and sent to the DB Sewer, the www.jspiders.com 4 Jspiders Author:-Shishira Bhat Training & Development Center ‘Technical Architect DBSewer does below things 4. Compile the sgt statement @. Prepare execution pian 3 Exeuk query or sat statement 4+ Stores the result or processed olata in buffix memory Ccunsor) > To fetch the data from buffer memory & cursor ana t fterak overt the cursors we use the methods of ResultSet Itke absolukl), getFirst (>, nextC) etc. > By default ResultSet clees not point to any record. Hence we need fo use tho next) method. > “the returntype of next() method 1s boolean ie nextC> moves te next actual record Tf it is present ana retuins true. > OF the yeord fs not present then it returns false. > Te fetch tne data from a particulary column we use getXXKC) meihoa Syntax = publte XXX getXxK CString colname); public XKK_ *K Cint colaum) ; The getKxx c) hod is overloaded. ~The one method takes String columnaame or celumn(abel and the other method takes ink columnNum or columalndex ex gel get Float cy; getBoouant getOntl; > Syntax of neat) is , public bookan next C> > THe absolut () method points to the exack snecord which is seat as an argument 2 the vetutntype of absolukl) is bookaa Syntax: public boolean absolut: ( int rownum); Ex: ys. absolut (12); YS. absolu& (Q0o)" SHISHIRA BHAT Technical Architect www.jspiders.com Program io: package org \j spiders. Abapp; Import fava: sql. *; pubic class Delt Product Demo t publee static voi main CString] args) a String clelitiqry = "cele from jjmil. product where category > ' household’ ” > Connection con= null) Statement stmt = aul; www. jspiders.com Ispiders Author:-Shishira Bhat Training & Development Center ‘Technical Architect final String ORL * "Jabe: mysqi: /locathost : 3306 ? user=root & password =clinga" 5 fry , f Class: forName C"com.mysqi.jabe. Diver con DnivetManager. get Connection CURL); stmt + con. creak Statement); iat nova > stmt. exewu&Updet Colelé@ry), ene +" reord/s are celtic") catch CClassNot Found Exception ©) . rintStack Trace C)" SHISHIRA BHAT sP 2 Technical Architect - C SQLException e) www.jspiders.com @ priatStack Tracec) s finally £ try z if Cstmt | = null) ' & Stmt.closeC); ¥ if Goa! = nuit) é con.closec), # a catch (SQLException sqie) e sqle. printStack TraceC: 5 ff Not = Ot is not a good practice touse “Yhrows” along with mafo method. Programil: package org: jspiders. dbapp; fmport java-sqi-*, import fava. util. Seannen; www.jspiders.com 15 Ispiders Author:-Shishira Bhat ‘Training & Development Center Technical Architect public class Updat: Student Demo © pubic static void main CString (I args) f Scanner scan new Scanner Systen.fo); Sop C” Enter 0"); String ta Scan. nextl); SopC" Enter percentage ")' double pere> scan. nextDoubke(); scan. closet?! String updatqry = update jjmil. stacteat ie set perc= “tperct" "t “where sid='"+fdt" 7 "5 Connection con= null’ Statement stmt = null; final Striag URL = "jdbe: mysql 7 locathost $3306 ? user> root & password =clénga" ; try t Class. forName con= Daivex Man: mysql - fabc. Datver"); + getConnection CURLY; Statement 6); exeué Updak( upaateGry)> Sop Cnorut” vecord/s updaka “} Pot orn # catch C ClassNotFoundeéxception 1S9LException ©) & ©: priatStack Trace (); 3 fioally ; SHISHIRA BHAT 7 Technical Architect .jspiders.com tf Cstmt {= oulld www.jspi e stmt. close C2! § tf Ceon) =a? £ con.closel)* y J catch (SQLException e) © €.printStack Tracey’ a 5 www.jspiders.com JIspiders Author:-Shishira Bhat Training & Development Center Technical Architect CommPt = > When we establish the Connection , by default the autoCommPt() modets enabled: 1¢ when we exeuk queries te result is commilka in the database % AutoCommit mode can be clisabud by using con. set Auto Commtt-¢ false); 7% When we disable autoCommit mode , then we have to explia'tty commit the results by using con.commtt¢ d> Program i: package org. jspidexs . Abapp; fmport java.sql.#: public class Fetch AuStuctent é p-s.v-m(StringlJ args) e SHISHIRA BHAT Technical Architect www. jspiders.com Connection con = null Stakmeat stmt = null: String selQry ~~ Seact * from jjmi.student "5 final String URL = "jdbc! mysqi : / localhost : 3306 } user=root & password =clinga “ ty: na 3 Class. forName( “com.mysq!. jAbe Driver"): cons Dniver(Manager. getConnechont URL)’ stmt = con.creak Statement): ResultSet rs= stmt. exevukQueryl selQry >; while Crs-nexte>) a Sting mame = rs-getString C"sname"): String id = TS -getString ("sia clouble perc = vs-getDoubs ¢ “perc"): rs: get String (4); “trade © "+ peret " " + stream). catch ( Exceptton €) © €. priatStack Trace C} £ finaly © W close all resounces 3 x 3 www.jspiders.com Jspiders Author:-Shishira Bhat Training & Development Center ‘Technical Architect Program 3: package org. jspidexs . dbapp; Import java-sqi-# : Import jave-util. Scanner * public class Login Validation ¥ Pisewem StriaglI] args) i Coanection con null; Statement stmt = nail, final String URL= "fdbe! mysql: / localhost : 83067 user root & password = dinga” > Scanner Scan> new Scanner ( System tn); So:pC" Enter your user name") Striag un= scan.nextCd! Sop" Enter password ") String pas scan-next¢): scan.close C2; String qrq*" Select * where me from jjmil.usec "+ try ie Class: forName C''com. mysql. jdbc. Daivet ); con> Driver Manager. get Connection (ORL): stmt = con.creakstatement¢): ResultSet 18> stmt. exccubQueryl gry); if Crs.nextc)) e 7* valid User R/ Sop ("welcome "+ rs-getStiing CL) 5 eve SHISHIRA BHAT Technical Architect fe (# fnvalid user #7 www.jspiders.com Sop" Gnvaid user" e catch C Exception €) f e-priatStack Trace) 4 finally @ Melose au resounces o Ng 5 www.jspiders.com Jspiders Author:-Shishira Bhat Training & Development Center ‘Technical Architect Progyam I¢+ package org.shishiva. Abapp ; import java -fo. FiteNot Found Except on ; import java.io. FileReacer; import java.io. ToExeph'on; Import java-util. Properties; ee class GetAuUsers ee Static veict mainCStriagl] args) SHISHIRA BHAT Technical Architect www. jspiders.com Connection con = null; Statment stmt nail; Properties props > new Properties C > final String URL >” sabe mysql i 7 locathost * 3306 "> String qry* "select © from frmul. user"; “4 fr= new FileReader (“config /dbconfig. properties "); Class .forame( “com. mysql. jabe- Dziver "J, */ con= Dai nage + getCannectYon CURL, props); stmt = con. creakStatement ¢); ResultSet rs+ stmt. execuk Query (Yry); wshila Crs-nexte)) ie String name = rs.getStving ("name"); S-0-p (name): ; catch (Exception ©) &. printStack Trace 0; finally £ byt if Ofef =nail) e fr closet); catch (B0Exceptiva ©) ©. priatStack Trace CJ; fl www.jspiders.com Jspiders Training & Development Center Author:-Shishira Bhat Technical Architect try if (stmt {= null) E stmt -Close 0; z if (cons = aut) = con.clo sec); 3 ¥ catch CException €) e.priatStack Trace (, 5 # Program 15 package org . Shishi Imporé java-fo.€ Import java : Fmport java.util. properties; public class ExecubSetct Demo preva (Strfngl] args) Sop (" App start "); String selgry > “ Select * from jjrall. employee “ FileReadex fr= null; Properties props = acw Properties C2, firal String URL= “jdbc: Mysql: / localhost : 3306"; by £ fr? mew FileReaden (" config /dbconfig . properties "}: props.load (fr); Class-forName € "com. mysql. jdbc. Driver"); con DniverManagen . getConnechion CURL, props); simt= con. cveabStazment (); boolkan result = stmt. execuklselQry); if (result) e ResultSet vs = stmt. getResultSet (2; while Crs-mextt 2 www.jspiders.com SHISHIRA BHAT Technical Architect www.jspiders.com Ispiders Author:-Shishira Bhat Training & Development Center ‘Technical Architect Stuag name = ¥s-getStringl“ename"); double salary = rs-getDouble ("sai"); Soplname+" ~ "+ sal ); I s catch ( FiteNotFounaException ©) @ printStack Trace ( 1" catch (IOException ©) SHISHIRA BHAT Technical Architect www. jspiders.com e-printstackTrace¢; catch (Class Not Found Exception €) e-priatstack Trace 6)” finally : dM clase au cos! SOURCES ons? 3 3 Program I6 : package org. Se dbapp ; Import java.io foaport java. iy Properties > pos Class Property Ready Vility gee static string getProperty (String key) String value = null; FileReadex fr= nail’ Properties Props ~new Properties); try € fr? new FileReader (config /dbconfig « properties "); Pprops-load Cfr); valua = props - getProperty (key , "No key found"); F Bak catch CEnception et ©.printstack Trace 0; www.jspiders.com Ispiders Training & Development Center Author:-Shishira Bhat Technical Architect catch (IOException €) €-printStackTrace (2; 3 nal " ty if Cfr! =null) a try z frclose cd; catch (IOException e) @.printstackTraceC ?, . Yetunn value; 3 s, public class ExecatDIMLDemoe f pss-vimaial String lI args) z Connection con=nall; www.jspiders.com Statement stmt = oxit; String diver = PropertyReadenLiility. get Property (“driver ")) String url= Property Reactex Utility . get Property ("Url"); String pass: Property Reader Vtilély . get Property ©" password"); [get username atso] String qry> "“dekk from jymil. employee ushers dept =" pool'’ aes 2 Class. forName (driver)! con OniverManager. getConnection Cuvi, user, pass); stmt= con. creat Statement (); bookan res = stmt. exeiuk Cqry); tf Clves) t int nord = stmt .getUpdatCount ) S.o-p (novdt " recovads deltict * catch CExeeption e) £ www.jspiders.com Jspiders Training & Development Center e.printstack Tracet ), 3 finally g dry é Ff Cstmt! >nul!) i stmt close C2; a Pf Ccon| = matt) t con. closeC)? i 5 catch (Exception ©) # e. printSlack Trace ? 3 Ry Prepared Statement :- dala/ parameter Select * from emp where td =| 41|—| Select ¥ from emp where td =|56| 5) Author:-Shishira Bhat Technical Architect SHISHIPA BHAT Technica! Architect www. jspiders.com = compile once Select ¥ from emp where Td = 2-» placeholder gu | execxC 41 paynamie data! paren 56 |» execuk (56) 2 maltitimes + PreparedStatements are designed to support execution plan + The advantages of exewtion plan fs the simflax SQL statement or query 7s compiled only once & canbe exewtcd multiple times. * The execution plan provides placeholders (7) te support dynamic data- % Any no of placeholders can be present which starts with index of number L % Prepared statement ts an interface which is present tn java-sql. package * PrepavedStatement is a part of JOBC API for 1 which implementation ts given by www.jspiders.com 19 Jspiders Author:-Shishira Bhat Training & Development Center Technical Architect oui fvent DG-Vendors as the part of JDBC Driver. * Prepared Statement extendas statement. << intexface >> java. sql. Statements H << interface >> jave.sql. Prepavect Statements SHISHIRA BHAT Technical Architect www. jspiders.com Steps for preparaStatement Stepl + creak an object for Prepared Statement Stepa: Set the values for placeholdets Shpa > Execute . Ex: PrepavedStatement pstmt = con-preparestatement C" select ® from emp wheretd=? 2 pstmt. setLat( 1, as); set dynamic data te placeholder. ResultSet vs > pstmt. exeubGuery()) “execute - Points to be considensa. while writing PnepavedStatement program : > The query of S9L statement along with placeholders must be passed while creating prepared statement object : > Dynamtc deta must be set f the placeholder before execution. + The no-of dynamic data & value must exactly match with the novof placeholders othexwise we get SELException. + While exewting the query we dont Pass tne SEL Statement for exeukQuery (I method. Ex String qry> “Select count C#) from jjmil. employee " ; Mload & register the dniver Westablish ‘conection Ucreat. statment / prepared Statement www.jspiders.com Author:-Shishira Bhat Ispiders Technical Architect 1g & Development Center ResulfSet vs = stmt - execu Query Cqry); int aeof numof Rec * rs-getIn-C1); J U/ close stmt & con tf Crs-mexe)) a Lcomerdaymaxa - qwasd Dejawesed v9 e1ep o1weukp © * | “ » t | rT Lo nepdyymare jus Jbsanbou = € a + ereaps el le a ' {ibjwousergosedord «vos = quasd yvawspe)s predorg 10864 Gp sani ducea nie airgiegh, 2veretae uawyegpoedauy www.jspiders.com es <= i fa é i 2 so Zi Technical Architect ] gmexarnidwes) »maxaynidwos| yrraxarnidwos| | - b 4 x3 cy £86) yepdoyrrera WIS Aeby yepdayrrana: ws [6 1b) qepdyymena WIS joownbie ou oe © aw qeng gees ves = quis VOweIES fa (o'o‘0'o) sanier wif ops rasey , eb 6uN9S quapnis J, (0 '0%0'o) samen rb bus quapnis -nw{f aqus qrasuy I, (0'0%o'a ) semen sth buns quapms- nuff ave qasus quawyez$ www.jspiders.com Jspiders Author:-Shishira Bhat Training & Development Center ‘Technical Architect fasext into jjmil-empioyee values C ? 2434 insext into jjmil.employee Ceid , ename) values (7 ,?) 4 2 to Select & from jjmil. employee where dept =? £ updak jjmil.employee set sal where eid Program It. package org -Shishira. dbapp; import Java-sqi. €; public class Pstmt Insert Demo SHISHIRA BHAT Technical Architect www.jspiders.com pes-vimaiat StringlI args) t psime= null; porty ReadenUtilily - get Property (* cbriver “); Reader UHlity . get Property Curl” ‘ erty Reacten Utiuity . get Property (" usex” 2; Class «for Name Cdniven ); con= Driver Manager. getConneckion Curl, user, 353); pstmt = con. prepareStatement Cqry 1; /® set the data for placeholders */ pstme , setString C2, “Kishor "); pstmt . setString C1, “st "); pstmt. setStriag (4, "cs"; Pstrat . sekS¥ning + pstmt. setDoubk (3, 96-12); /* exeuk the query #/ int novi ~ pstme . exetut Updat (); Soop Cnori+ " records insert "); catch CException €) £ eprint Stack Trace C y a www.jspiders.com Ispiders Author:-Shishira Bhat Training & Development Center Technical Architect 3 finally e Uclose al resources 3 g 3 Pogram 18 : ‘i SHISHIRA BHAT Package rg. shishiva-dbapp; TRA BE pubic fatexface DBConstants Technical Architect = www.jspiders.com String MYORIVER =" com.mysq! «jdbc. Driver" > Striag myuRe >" jetbes mysqli 7 localhost +3306 ” String MyuseR =" voot Sting YPASS =" ching" g package org - Shishi Import java-sqt.m Import java. atl import stati jelbares rane 01g -shishira. dbapp . DBConstants #7 public class PstmtSelctDemo f prvak static final String see "“Selct * from jrmit- employee “+ " eshene Bia 2"7 pubuc Slatic void main(String lI args) Ly Ganection con =nuil; Geamer scan = new Scanner CSystemin); S-0-p ("Enter employee Lo")’ fat id = scan.nextInte ); ty t Class. forName CMyorIVER) con DaiverManager- getConnechoo CMYURL, MYUSER, MYEASS ) PrepavedStatement jestmt = con: prepaveStalement CSQL); psimt « seeInt C1, tol); ResultSet rs = pstmk. exeu@ucry ¢) tf OS: next or) ee String came = vs .getString (2); double sal =rs-.getDoubkl "sal "2; www.jspiders.com a Ispiders Author:-Shishira Bhat Training & Development Center Technical Architect String dept * rs .getString C"dept"); S-o-p (names ” aaa - eve t S.o:pC"No data found”. + dept); catch ( ClassNotFoundExceptioo €) z e. priatstack Trace C2, $ catch € SQLEXception e) @-priatstack Trac eC! z finally z UM close at the ¥ eS 5 SHISHIRA BHAT Technical Architect www.jspiders.com 3 Batch Updaks : >A batch update is a batch of updates grouped together ,and sent fo ihe database tn one “batch”, rathex than sending the updates one by one ? Gatch processing Allews you to group relaid Set Statements fate a batch ana Submit them with one ca 4 te database. PWhen you send Severai SQL statements te ihe database at once , you reduce the amount ef communication ovexhead , thereby improving performance. > Sencung 8 batch of updates t the database In one go, ts faster than sending them one by ene ~Y There is (ess network tvaffe involwed in sencing one batch of updates (only 1 vound trip) > You can batch both sgu inserts, updates and dektes , Ot doesnot make sence to the batch Select statements. > There ave 2 ways to exewus batch updats. A Using statement #Using PreparedStabment + The add@atcht) memoad of Statement or Preparedstatement is used fo ada Individual statements 1 the batch > Syntax is public void adaBatchC) The execukGatth() fs used fo Start the Cxeution of ak me statement grouped www.jspiders.com spiders Author:-Shishira Bhat Training & Development Center ‘Technical Architect together ~ Syntax is : pubic fatl] executcBatch¢ ) > he exewulsBatch () vetums an array of integers ,and each element of the array represeats the updak count fer the respective updak statement > Just as you can add statements jp @ batch for processing , you can remove them with the clearBatch¢) method. This method removes ak tne statements you addled, However you Cannot selectively choose eohich statement to remove. Program 19: package org: shishira. dbapp; (import static ovg: shishira. dbapp. DBConstants © ; Import java-sql-#} SHISHIRA BHAT Technical Architect www. jspiders.com public class GatchupdateDemo t prs. v: main ( StringlJ args) é S-opl" App started"); Connectiva con > Prepared St at pstmt = nul; String insextGry > “fasent inte jjmil. student values (2, ? try é Class. for Name C DRIVER?’ cons DowerManager. get Connection ( URL, USER, Pwo); pstmt = con. prepare Statement tnsertQyy 2; 7# Set 13* vow #/ pstme. setStrng (1, "see '"")' pstmb. setString (2, “Pavan")* stmt. setDoubleC 3, 51-4): pstmt. addBatch() > //add 45+ record © batoh 122>"2 Pe Set AL yous +/ pstmt setStringl 4, "s107"); pPstme. setstungla, * Anish"); pstmt. set-Doubk (3, 66.86 2 pstmt. addBatch CI) 4 add 2° nacord te batch Me Set 3°" vow */ pstmt. setStringlt, “sio3a")? psimb. setString Ca, “Niki”. pstmk. set Double (3, 90.86: oe www. jspiders.com Ispiders Author:-Shishira Bhat Training & Development Center ‘Technical Architect pstmt -addBatch(), Gadd 3° row t batch pstmt. exeu&GBatch 0); 5 catch C Exception ed i a Ts iP atStackTrace 02; SHSHIRE BHAT finally Technical Architect & www, jspiders.com Wclose au resources 3 ; > By using prepared Statement we can use singk query but multiple records can be up tor inserkch ov Ceuta at a time. > Gmbination of are nok possible Ext | inseat, 4G , 2 updat fs not passible > PrepavedStatement with Gatchupdates gives high petformance. Singleton Des fatten <- Program ao: package 07g: shishive. cbapp ; uw ‘singuton pubuc class Vishweshwariah é fm 4. #7 private Vishweshwaviah C) = I ie 2 es Private static final Vishweshwavianl) ONLY-ONE = new Vishweshwariah Cr; ye 3. #/ public static Vishweshwariah getSnstance C2 f yetutn ONLY_ ONE > 5 3 www.jspiders.com Ispiders Author:-Shishira Bhat Training & Development Center Technical Architect Applying Singleton Design Pattern for JDBC Connection = Program 21; package org-shishira. dbapp; fmpork java.sql. * | am class DBSingleton Private static fina! OBSingletoo ONLY-onNE = Mew OBSingietonl> privat Connection con; Private OBSingleton () é ve é Class. forniame C"com.mysqi. fabe. Oxiver"), Haon- state con = DnivetManager. getConnection C"fdbc: mysql: 7 localhost 5 8206 2 uses voot & password =dinga "2; I Catch CExcept f e-priatstack Trac 3 at pabiic stat Singleton getInstancet ) = zelwnn ONLY-ONE > 3 Mnen- stat c pursue Connection getCon > e retunn con; 3 5 SHISHIRA BHAT Technical Architect www.jspiders.com Code to access the Connection: Public static void maia (String (I args) & DBSingkton dbs = DBSingteton . getInstance Cy Comection con = dbs. getCon (); 4 OR #/ Connection cont = DBSingleton - getOnstance (). get onc): J www.jspiders.com Author:-Shis| Bhat Technical Architect TDPBC Transactions i- Exi- con. setAutoCommit ( false); Bogle opt op2 op3 * SHISHI} Technical Architect www.jspiders.com Ena. - con-commtt ©); catch CSQLE xception ©) ft con. rollback ¢ 2; u; > Of au the operations are successfull, it wilt be commit.d. nagement and Savepoint - sel of actions to be carried out as a single, atom*c action. Hons ave carried out, or one Of them ave. un Of when transactions ave necessory ts the example of > TOBE trans. > A transacton 7: > Either au of the > The classic exar bank accounts. > You need om one accound te other actount. You do so nasfia Rs 1000 f by subtracting Rslo00 fiom 1% acount , ard adding Rs 1000 to othex account > Of the process fails after you have subtracka the Rs|000 from the 15+ bank acount , he Rs lo00 ave never adcact to the second bank scount . The money is lost in cyber space 7 Bo soe this problem te subtraction and addition of me Rs (000 Are grouped into a transation OF the transachion Succeeds, but the addition fails, you can“ yollback “the first subbraction > That way the database rs left fa the same stalk as before The subtraction was exeuhd > JOBE Transaction let you control how & when a transaction shoul commit fato database 4 Transaction block start Usgt fnseat staement- USGL updak Statement UW sg delete statement U1 Transaction block end 2 In simple , TOBL transaction Make sure SQL statements within a transacton www.jspiders.com Ispiders Author:-Shishira Bhat Training & Development Center ‘Technical Architect block ave all executed successful, ff either one Of the SgL statement within transaction block is failed, abort and nollback everything within the transaction block > By default when we create a DB Comecton, 29 means that whenewerwe cxecuh a query andit’s compukd , the transach’oa commit 7S firea automatically. 7 So every se query we fire ts a transaclion and if we ave running some DML or DDL queries , the changes Are geting Saved into Database after every SOL statment finishes 9 Sometimes we want fe a group of SL queries Kung fo be part OF transaction go that we can commit them when all quenes runs fine and if we get any exception, we havea cheice of rollback all the queries exewba as part of me fe vans fn auto Commit mode transaction. TOBE Transaction Management > To enabla manual -transaction support Tstead of auto-commit mode thak the Tose driver defaull-, use the connection object's setAutoCommit ( ) mathod. POF you pass a boolan false to setAutoCommit ¢) , you twin off auto- commit: - > Yeu can pass a aan trae te tunn it back on again > Syntax ts public vi & id cekAutoCommte¢ boolean ‘ralue) ; to Commit € false); + con. CommttC) @ PollBackC); Once you are done with youx changes anc you want to Commit te Changes then cau commitc) methoct on cennection object as fellows : con. commtt ©); > Otherwise to vollback upaales to ne database made, use the following code? con. vollback C ); Program a3: package org. [spidexs . traxapp; Import java. sql; import java.util. Scanner ; public class OBC TransactionDeme é p-s-v-main ( Striagl] args ) 2 Scanner scan > news Scanner ( Systemsia); Spl" Eater name"); String name> scan.nextc); Sept" Enter Ib"; Jat id sean.nextdak 6 SHISHIRA BHAT Technical Architect www.jspiders.com www.jspiders.com aa Jspiders Author:-Shishira Bhat Training & Development Center ‘Technical Architect S.o-p C" Entex percentage"); double perc > Scan. next Double ( ); S-0-pl" Enter stream"); String stream = scan.next0); Sop” Enter city I String uty > scan.next 0); Sopc" Enter stat"; String stat =scan.nextC; Sio-p ©" Enter country"); String country = Scan-next Cy Sean .closet; Ganection con = null; Prepared Statement pstmt > null; Prepared Statement pstmt a = Aull; String MsertGryt = "fasett into jjmll. student « education_details " + “vatues €2,2,7,99; String insen j2.= " Insext Sato jjmu. student. student address “+ "values €72,2.2, 2.902 final String URL * “jdbc mysql: H/localhost 73306 ? user> root & password> clinga" ; ty é Class- for ‘Com. mysqi- jabe- Dawver") con= Drivertanager- get Connect on CURL); 7# Transaction begins */ com. setAutoCemmit (false); SHISHIRA BHAT Technical Architect www.jspiders.com operations pstmts = con. prepareStatement Cinsext@ry 1)! pstmt. setString 6, Rasy name)’ pstmt. . setSnt C4, tt; pstmt. set Double (3, perc); psimts. setString (4, stream) pstmt. execat Upaat 62; Yop eration pstmta > con. prepare Statement ( insect ry 2); pstmta - setIat C4, ca); pstme2 « SetString (2, name), pstimt2. setString (3, city); psimta. setString (4, Stat); pstmt2. setString (5, country); pstmte. execakUpdat (); 7e transachon ends. #/ www. jspiders.com Ispiders Author:-Shishira Bhat Training & Development Center Technical Architect con: commie); Sine Exception e > a Print Stack Trace 62; ba (S@LExeption ©) 7 SHISHIRA BHAT Con.rollback C2; poe C" Transaction failact “J; catch (SQLException ex) ie er. printstack Trace Cd; 3 finally 4 Technical Architect www.jspiders.com Uelose atk TOGC resounces F 2 - SavePoint i SavePoint sp> null, Transaction begfo = opt op, ops ——> sp> new SavePoint ("one"); ors x ops con. commit)" Transaction ends. catch CS@LException €) 2 ff C spl = raui> con-vollback (sp); Con.commetC); § eke cd con. vollback¢ >; www.jspiders.com 3} aT Ispiders Author:-Shishira Bhat Training & Development Center Technical Architect Tetadata > GD Data about a cata fs calud as metadata. GA database contains mang tables & able contains lots of data. D Apavt from data, the DG and table has its own alata like no.of columns, datatype of column, length or size , 78 The column primary key? etc 0 These dataare cada as metadata. GD We canget the metadata fnfo by using below 2 interfaces ODatabasemeta0ata O ResultSet meta Oata D Bom are present in java.sql. package D Database Metaata deals with the metadata infs of DB like DBName etc O The Resuttser Metadata deals uxth the metadata info of the tabu like the no-of columns , column length ete. Program ati Package org. shishiva. dbapp; Fmport java.sq pubic class MetaDatademo a private static final tring URL = “jdbe: mysql: Y locathost : 3306 ? user= Tooke rs password = dinga"; Private state final Sting DRIVER ='tom. mysql. jdbc. Driver"; public static void main CStiagl] args) r Connection con= nuit; fy e Class . forName ( DRIVER); con = DaivertManager. get Connection (URL); DatabaseMetaData dbmeta > con. getmela0atac >; String dbname = dbmeta. get Database ProductNamec); String dnivexName = cbmeta . get OniverName(; S.o'p CdbName +" "© dnivewName }° a catch (Exception €) e e-printstackTracec 2 § fenaly e SHISHIRA BHAT Technical Architect www.jspiders.com Uclose all nesounces J 5 5 www.jspiders.com Jspiders Author:-Shishira Bhat Training & Development Center ‘Technical Architect Program 2 package org: shishira- dbapp; Import java. sql; pubic class RsMetaDataDemo e rivae Static final String URI jabe : mysql: / localhost : 3306 / {mil 9 q et ng mi be ij user=root & password = dings") com.mysq/.jabc.Oniver "; Private stahc final Sting DRIVER = p.svimain€ Stringl) args) Z Connectioa con=null 5 Statement stmt = null; Selact * from jjmil. employee SHISHINA BHAT String qry>" try Technical Architect g www.jspiders.com Class. forNama ¢ DRWERD, | con= Daiver(Manager. getConnection (URL); stmt = con. crea! Betatenect 3: Resultset ys> stmt. exewlcQuery Cqry); ole ysmeta ys. getMetaData ( ); Result Setmeta int neColamns= rsmeta. get Column Count ¢); String colName= rsmeta. get ColumaName(3); ao CneColumns + "+ colName); catch CException €) t e-priatStackTrace¢ 2) $ finally = Y close ak resources } a www.jspiders.com

You might also like