You are on page 1of 61
Sa SS ten ml at + re tl Sima ne tats Setecaierw ona omceenpeti ine enc ota sen ‘Riarconecrinoarsatr agin om efor gam edd eh kp, [Seif tops ck: Outer erm Ba rae emerge sae eraraamn “om ee op nd : oF stat eed that gn csr enamaniong el sans Sen een) Galt) ets (Sicdesnt gata ag eambapag ms {Foccece ry ee. 1 Ste se etn, Sa SS ten ml at + re tl ee i ara tec on oe seve ‘Riareoneerinoarosanran ogee [Seif tops ck: Outer erm Som an oan ont sth td hcg Ao “dnt (ena) atc ep pd Sain meme sea aces ae eioegmint SES eee SE teem ert (son Oh a le ee [nteeielentgn ii), Coes’ tang cn tenement tine. Eee ante ‘0.726 tame ates at ese area no atm yee ft nt ey? oe aS 7A a ne “Micon uni enn oi inom Sibeaneter stan FOMD es ies eect ap, “emttare or mers shone se ‘Shtaets nt nestle nad sc in ins io Een mente np a 98 ~tpsteate te alta EEE tp ‘ican ne he rmersrup ent a itt ae Se ce J J ‘enone ate. domaine Sorc do en ton nasi a Sica “Sieg enh ste cops ccm tn cet re es Seno era” what dtner bile praet an task Pont ett fas tsa nd oF eicrareediy Een as eva Company staat Horace (tnt pies eatarenjoreereneDpmal.com: ‘ort ar eaten poh ge See SSS Specs ene ecm, FO canteen seein tt "Gestpepsw en paem caso nace cnt nnn cnet me toner onrh | Icom mated hta Senn ere aaa The Mateos to tood the Jv as nthe following the stuatons an fw lng heen 18 stoner cate ot ‘eg tmecane (a whenwe pce cgsnong pment wit slant) tod “imate, te mecie angMond ecea tern Bm (2 naetemartanametonf cane ep pet ie nett ra sete a anther NE tn =n a te gt Seep cpoi aig a ae Seen he ma onin nt maitntodn in mateo et EE caret epee ae ‘styenorosto re Tinea macau [oe Omer atest soe =o wetctoc newc\nconrevenitane ie Mamita) naienni nine opam ena 00 RAMI squat honttadntnnverin st he rer te remand pts at) ‘oem ‘sa foc spe apa SUSIE a an ea ge AP! (Beiction Programming ieraee) iSeaesfatanonronstonenctonse st mE tree an tec ot ea nh Peden Pn Ps ieee J eStpentemarea Viera tramnrnape ‘ts fren oman whl punsahan nena amen ‘Sinan tae ‘ata ta “Tobe one cet nb le wb adie nd ee “ovtp eerie ocimtne mie sine se) apace: anatomical re vom acter = i ae i cee LA) oe ert etd espa gna te A a a Saar. eins tsa tr rn rit rns te ‘erat ope) ‘arbres morose be “mae posi evar oa os — aan aa tee | ———— ‘Sinn Saute as} ye rnin tein ‘Tose ecotent fe foe waver wire nm menwenine near Stites ecenoorene en ptt tome SES. oo unSsitntiii ‘mramin weno oop enna nono cement Games eon te i ig comm yong mae mad Seafoam ae) eran lore ebm soem tea te ogi ‘ge caine ranma an wt nae cone =e aes Sos ‘NoonnaipaTnormonren pce Sratmea oom san Sapam rine a a lle pe dg tnt hearin ee re Te Shantetn i lpn ets nett casted mang ek ietcaocem pre ne Wstleagcete “prema ? edieanae Wtepaeeet) ‘Seana ymca nnn ei “eo ttn eatin aoe ‘aPC —spopcs stamina wma ee Wrstoceatten "aio acisgpaton ) "henson ce acm rab Sessa hs wating ‘ite amin = red) {2g omnes ei Sat 27a 29) ‘ng wentengteeoin sachs 3). nies Petieencwion rca So DRM spo FfPatonmoutarete bene or " lyre tema ninadng ete ‘oor os bras wate ames Senecio eae oe ae ———a) the parameters (2 SOL query for PeparedStoment bec can represent oly Input they can nt represent SOL Key words, table ames, cs memes ah selec romadent where sno? and snc? eps let * from? where sno>+? (rai) (oath a8 slat from Stent whore >=? and <7 iva) eats select #227 snore? nai ‘The advantages of PreparedsTatenent bj {)Alows to work precompiled SOL Query can represent both stati od dynamic SL queries with params) ‘or with hard coded sof ced ints Does not aise SA injection Problem ‘No need of convertinginput woes os equied forthe SL very 1} Stabe for enecating same query fo ipl iter with xn opt oF np {)stitblefor insert Dae vals. bate cl by ealecting then fom ender erent formats 4 Suitable forinserting Large objets) oD abe cob atic te alference Senplestatemant abject and Prepredstatement? Simplesateent PrepareStatement od} (o)Doesnot old any recompiled gery {othotd one recompiled Sa query (br canbeused onto cxecite static sat queries _| (8) Canbeusedto eects both state dynomie SOL queie (e)may aise Sat jection Problem doesnot raise (chinputvatcs must be converted arequited for | (d not equiv to conver, the stn ‘methods wl take cero conversion (e}does nt params nthe query (ohatows. (W Worsutaieteerectessmesatquerytor | (0 stable "util teste with same pts oF Sihinputs (a) not suitable for doe vttes insertion (table (by notsuitabefor Large obsfies insertions | (h) stale (0 One simp statement ob canbe wed iF Every Preperedsatement obj represents to exeate mates quels one by ne bbe used to execute maltpe queries one By one ‘oe pr-compled SA query 50 that objet tocrecute mole OL queries, we eed multiple Proparedsttement objets sve Developers in restime donot work with Sk prompts det. femd prompts} ‘They preter sing GUI Jove tools to make operations easy Towork with these tol stor sat rowiedeis not ered ‘8 SL dvslope for Oracle shen Orca corp eperat alton upto Ne), yal 8 workbench ien by MSQL DB fia? ‘SAL yog or mya eperate statin) ‘Toadtor oad seperate) oad for yet Penn for pstreQL. wil ome with Poor winter) 51 deine for rae ‘Comiood tom temet: Mtpt/wi.cracle name cont ->eubmit semameseesmord->Testoconnet sepa) rete Db abe ‘pad cont > ah clk ables anew tab ‘ep perform llCURD operation on ab abe mel see memo - resting at (Project isin Shr Se umber cop ein ro Ss bw tov | rox tn| TEPER | adem npr nes 3308 my Grsonogel Dera, wo ate impel rl mycorate peo set cee ot saan eres) sat ate) tater shone chen bot ees “nathan vent nr er Ace Test {it he tmp condowiots ‘tate nny Tes Test met iat ns msgs cao sre huge anon oat Tepavabe/ tie eit cnvehae omen tana san et mre wo be in out ition of mys OB s/w and bens of rae D8 sw? Procedure tocreatelogal DB having table wih records Hep] make sre that mpl Dbs/w sisal onditisunrng ede seb Ww) en eee —- ee 7 aos, pane eens ae pats ae ane: ps) ete abe stent hinges. ‘pranayama Ss vada Ht erro rowteced (3 0, ‘rar ae ler 789 ‘er Ow fee 0) me ommte ‘hero Droweaneced (2200) Pocedur to rea lopical 8 having Db able with records eg ml woah sept] make sure that mys Db s/n ands unig mode ‘ep ch al woberch and eae cane Sor toner pen > mpl wotench > crete cnncton > smi ‘as atanvacionnanesconl => prsret > teonntn ch pt cute ag sd a ge 8 oe El mS meme ene th in > oy cin eg) > chek abies econ “asus iinecatones—s ys ‘08 nen sepente ps He Tos => Dew supplied typet mechanism based je die sf for mysalis cle Connector} Ivcceer etals_(walnatcome alongwith maatinstalaon) “ver dasname:s comme bbe (or) commyslebc iver Cit jdbempel//opeatb8 mame>. or acl meal DB fe [docs shosiames epdéressport noel name> fr remote myslDb s/w) hostname oripadessmachone rd pero of mys Db sw where lar fies: myegconecarjoe 021 jr (supports utolodig of river cass nome) [elle fomintrnet > mnceestry.om) ‘nto fmntepotor con/atitae/nysl myscl hese colum vas re epee rom ends. those colum velues canbe ured and outside and DB uo identtyand access ‘hetalomatan ‘pr sadhal, otc panko, banbccount able andet Surrogate ey crm “>the at ey column whos els ee darcy genet he dering Ob ‘cnn orprolet without having any busines meaning Surat ky coum ‘ihe ctu uel or be rm enduer-witbe ponerse yeaa by dering Do afwor Projection. A indent canna incement rambe aa hibernate generators random number sven by Apporjet Latins taking natural key column as rary key clan “> ves are quite lengthy, they need mere memory ‘3 these ves ae having busines mening ana toy wl be changed becot toate buns polyes nahi procs: dara tet dependent (otis and jv ses (ery ony) ‘Thee values are exerted fom ender tender faites record inerton wl rote Do not aka tra hy cola primary kaya vay prfore tating ‘suropte ey clan as clu ‘Advantages faking surrogate key coum a column Vals are very sal So mech memory isnot required No business meaning. they never change ‘Sct epee rom endures ocrd earn i pone thorugh ender Tsot supplying eta Ota. SaL> reste sequence stad snes start with 000 increment by: ‘Sequence cesta sept) develope incr quer bated appaton using PreparedSttement oj ving inserts query sa query 3s shown blow. ‘>the oly possible reapratiea constrains fre pthc ke rat statin ting INSERT STUDENT. QUERY "INSERT TO STUDENT VALUES notes 8 egunee enor aware of wheather peal lue pun by sequence linseed or not, deleted nc. Sot away generates nest umber insequeen note Once supports sequences. but mya dos ot support sequences, 50 my [1% cothovng aut increment constraint tise values tothe col the ident cola wllbe generated stomatal) Ima workbench» go stent db table settings > goo sn and ele (astoinremet)~>appe step2} develop appcstion using Proparedtatement ob having folowing Query. iat state tinal tng INSERT. STUD QUERY INSERT INTO STUDENTISHAME,SAD0 AVG) VALUESE2.2°: ee uses prewous vale forms Te natant sander umber though code oranda) >< foster) rat statin! String INSERT. STUD QUERY" NSERT NTO STUDENT VALUES2.2F Monta) orconpreparetaterertMSERT.STUD_ QUERY set vlues query params iostensin rac, new RERUN). 20000); // 10,929 Poses prsesring( odes) Fandom las generate random number pesetoa a remot uniqee numbers for niqu number ) Sevrope custom code ore third ai rearacing wth utile Ob fs “Gwinn Aponte tee bw rend Sinan chon me cance mec cn ccs Sate he, neues esheets oe inept een eft uy on ene wh et ‘ee on cndaon mepessacoen’Pramsoe dese eccrine 1 ‘eerioe mieten neh eso ‘un nt henge ban el i lb ano et ik se Kea manatee ye SE Antares non be TE Space ant mye woh peg Donat te 08 pt ret a ne ‘Weecomome eat nested whet ‘nexcoun daien anc nth cre lmao ‘timeout ae tncin my waco (non tot Prom NY mame teeter = yon pest ey wt SiH) eink). ya roger om oc bie we wee Sela * fa eto Sats ‘hei gun et dng yon nme ated an ree wh (eringlsatenet jc out te eed vat carro mal ob ewe eno ‘ecto untried te Prepeesetemer ome rete ce 2 tre i opr finde coms ce lean a hasan nary x —— reveal ur oop froccece appeal ‘eer SreTtysabetantreoe ~ shame, 20100 20 oa pin ae dee ne nd ~ nar rng ok ed pn bet wn on tn Sst tse at aed leo, Si Ban wep ape OHO tae date eosin ptr ede» acum! toate pelsarmimtae 900815 te ig Signa wan ma the 8 gy od ng ‘tats dec th ott ning Do gat wacom ‘sou er ena opts at eure wi tee poe So 2 yas oe tewcese ‘eseee th rearacing wth utile Ob fs cohen Apconee wh mtse Ob f rendd monsdbg mean ate mpl ie co jc Steer te, epunsaement ete ee ane sini tp na mgs ajc fact SL gy ony fe wh bt ‘vege candor heaeterenb eerie persion csi ‘wowing moana eats ernest ‘nt hcg ban el at a ano tr ik rt nti scates ye Endres mere nn bien SE Section eng ct caer stent ce one ‘rome nebo ‘neko dh leln arc nith rcs [cont ‘retardant oaths (non be ntact dee Pima Ny sn meme mi) eee tr See ee) tena) tinny) Since ip) erin ND. tldertnve} sent om “som ne eacecufcnolemamenes) we? aS} me {ermal tines nit ef nus. Soe repeater a Sraniemeeer mas casceeacetae sy eee eee cease cocecesase enone cama ae ‘note: upto oracle 1g there sno support for indentity cohums.. oracle12c = er ‘whe wen 008, 2000 000 ow repteatin Ota te as we Reo ern tes Seigler bad pc beaten oper ‘tenet apes he tan shea dened al, flim Of ween 8 04108 taeda orn pre edo» ety oe! 2600189 Spalyymumeae og sosognis ote ig Soe tear we canna tae he SL ey so hing ‘toi dnt ters tt rh Df paw vr campe ‘tap bece ater bong tour a Starport Sie twas Og ose ‘ote (ei) i ge date value athe ova. Dat object a rapretatement object ‘gery param value he be drier insert the date vl nthe pattern hat ‘dering sf suppor. setDatel ooo no> ob of na sg Dte das, has the io ove sO ate andes. Date? 0s) jie basal “Dhol bt dateandtine | a) Had ony te ot thetine connotusedon Peter Bean ised sed operators Geomnetbeetasguery |e ene. deromotcinprocoet) Gniperotinmacionte | e)scasotinauttote Javauthoate() Jnvn.tme > ortime values FaveachDate > fordte luce ce Fovaseetinestam >for date andtine voles ald ora Sl dat type or dteine “ate > for date values Standard Procedure jb driver indepmdent and 0s) independent) IniDbe hop tedevopment tose date wlies to abate cols nduser tg date abet ert ipleDateFormat 2 wows Esp Pere \ Jvauoate dae oj ne an poset} Tay) Heanvering stg date val vasa sso ‘Singita 21-100" a ‘SimpleDeteFrmat stone Simplesteformat(s yyy [olin pattern of ot Jivaut at test parle Sytemoutsitinua The past ths thes gen ‘Sing date nthe specie pattern ‘aways wits jovautl.ote and srdconverts tint eatDate Jaen ate dans wth poche ames ober inthe joao avoid ambit eros Ieonvrtng jovi. Ate clas blo as. Date ies bh lengmaned-getinel) eno millsconds that ore osped b/w ian 13870 mig 0-00 hoursleochstanra) ond b's detetime JnvaseoDate ono vas. Sytem grin ate" In afin alte ad ne te myst ‘wale rombersdes ei th eapect t FAOINSd) ——_Aotheapoch standard 970 Jan 6 midith 00-0 hours pat tne S84 ingot vl pattern He tenitcan be converted recy to Uva agiate asa with ot covering jaa cas object Sing am 19-10.25 Ime Md Javaal.Date 2novasqhDat al; ttc method Sptemoutrint sl dated") \Weitea J08¢ App te insert 008,008,001 date vals rom use along wth pane, ee Seas es Dol" ymrewnas [Sms dare 2) nnn oe ate ‘4 (iph) —> enerate ving AL or date prone te Bom de tpca ) (CREATE TAMLE PERSON. DATE TAB (CREATETABLE'nsn4d person dat af'( Lee va eee TE "pi INF AUTO INERERENT PRIMARY WY, rae varenarat0), boone vacant “foume: vane), toeomre, ote VARCHAR, borate) ‘aeare eauENce PERSON pI0-S£0 tortor oa rom workepce] Retrieving Date viaues. For this we can use either SimpleSTatement object or Preparedstatement obj = if urjust reading and display date values... with out taking date value as the condition value the prefer Simple Statementopiect/Prestatsat€nt object, otherwise prefer using Preparedstatement obj. =>After getting Date values to ResultSet object by executing Select SQL query if we call rs.getString() the date values will come as string values having yyyy-MIM-dd pattern Jif ‘we call rs.getDatel-] method then we get java.sql.Date class objs. having yyyy-MM-dd pattern asinternal pattern. =>calling rs.getDate(-) method is good becoz we can use the recieved java.sql.Date class obj to present date in different formats as required for the enduser .. by using format() method of SimpleFormat class.. SimpleDateFormat String date value —J> |-sparse(-) =p java.util.Date obj java.sql.Date / SimpleDateFormat aay Sting date inva. uti. Date 6 eo ormat) value DB s/w independent and JDBC driver indepedent procedure to retrieve and display date values from date data type DB table cols. oracle Db s/w java.sql.Date obj sage java.text.SimpleDateFormat ae sringdate gm Se Seros089 Insinpleatrormat le ae eee ose pnasing |--> public String format(java.util.Date date) ta xX ‘>The Date patttern placed in SimpleDateFormat class obj will be used as the pattern of the input date while working with parse(-] method. and the same pattern will be used as the pattern of the outout string date while working with format(-) method... enduser ‘Assignment Writing a jdbc App to get person age in years based on the given person Id? (Use the Application Db table) a} Using DB s/w specific SQL query +b) Using Java code (DB s/w idenpendent code) 29) Using DB s/w specific SQL query ‘quer {refer PersonAgeCslculatorOracle java) ‘SQL> select (sysdate-dob)/365.25 from person_date_tabl where pid=1; {svspaTE-D0B)/365.25 207739647 query in mysql {refer PersonAgeCalculatorMySQLjava) ‘mysql> select from_days{dateditf(now(),dob]) from person_date_tabi where pid=1; (or) select datediff(now/),dob)/365.25 from person_date_tab1 where pid=1; [as ja a ) Using Java code (08 s/w idenpendent code) Write java code for this {csys date in Ms>- )/(1000*60*60*24*365.25) (refer PersonAgeCalculatorlavaCode.java) iffrst=null) iffrs.next()) { 1 get System date in ms sysDateMs=new Date().getTime(); ‘// get DOB from from ResultSet udob=regetDate(1};// java.util.Date cass ref variable dob) i refering java.sql.Date class obj Jas super class ref can refer sub class obj dobMsmudob.getTime() ‘System.out.printin("Person age::"+{sysDateMs-dobMs}/(1000*60*60*24*365.25f)); ) else ‘System.out.printin(""Record not found"); ) wit ‘Working with Large Objects (files) Larget objects(LOBs/Files) Los. av files :: audio video files (Binary [Character Large csvfile: coma seperated values Large object) Object) {eg:: image files, (eg: text files, Rich Text files (RTF), audio files, video files, csvfile and ete. av files, and etc.) ‘=> All major DB s/ws are giving support for LOBs by supporting data types ‘alled BLOB and CLoB => while wor trimony apps{match makings), job portal Apps (like naukri.com), social networking Apps(like fb, profile management Apps(aadhar Apps), e-commerce apps and etc.. ‘we need to insert and retrieve large objects... =>Simple Statement object SQL query expects files(lobs) directly as input values... but that not possbile..So we can not use Simple Statement obj to insert large obejcts PreparedStatement object allows to set streams representing files as query param, values .. So we can use Preparedstatement object to insert Larget objects. noter: The Simplestatement obj SQL queery does not even allow streams as inputs values..it expects total file content as the input value.. which is again not possbible... Streams =>Streamis a continuous flow of data... and acts as pipelines b/w source and destination using we ean send/recieve to/from Destination. tava Rep le /ay/Obie/oteton) Fan ‘Two types of streams based on type of data they carry (a) Byte Streams ‘These stream can carry both binary and text data». ‘=> Here InputStream are given for reading data and ‘Ouputstreams given for writing da eg: FileinputStream , FileOuputStream, DatainputStream, DataOuputStream_ ‘and ete. (b) Character streams ‘These streams can carry only text data. ‘=> Here Reader Streams are given for reading data and Writer Streams given for writing data 1 FileWriter, FileReader, BufferedReader, BufferedWriter binary To set input streams representing files as query param value we can use ppaetsinanysreamt sam ssn Seam | fyi ard 1->param index text 2-rstream 3>length of fle (from the To set 8¢248%reams representing files as query param value we can use begining) ps.setCharacterstreami.,;-)/ps.setCharacterStream(-y) (oF) for character/text data. ps.setClobtI/ps.setClobt 123 42. JDBC driver and DB s/w independent PRocedure to insert image (BLOB value) to DB table col stepil) Create Preparedstatment having Pre-compiled SQL. query Preparedstatement ps con.preparestatement( ISERT INTO SHADH_INFO VALUES{P0_sea.nexTVAs2,22,2)" step2) Create ByteStream representing image fle of the file system 1234 InputStream is-new FilelnputStream("d:/images/photo.jpg"); step3) set values to query params ps.setstring(1,"ramesh"); pssetString(2,"hyd");ps.setFloat(3,600000); regNo(pk)(n) name (ve2) addrs(ve2) income{n) photo(blob] ps.setBinarystream(4,is) = ramesh ‘600000 s {Since lobs are tape) execute the query _ AS sete rey Int countp.executeUpdtet~ AS in Dbsfwn * Ainterally stores the burden on Ob s/w inthe frm of wilincrease. (Pde (ages hein) nary info), varterrenes bad) LR A ‘>in oracle Db s/w each blob /cob value can be upto 4gb ‘= mysql Db s/w can notRie siz blob or cob vas note: Storing LOBS (files) rely in OB s/s wil done only small scale Apps. not forage scale Apps... In Large scale Apps flles "Matriymony App (standalone)~>Go for BLOB,CLOB values este sen ad Ce rane en tz ete se ae (colleage Apps, samall university Apps) Matriymony App (web based)-->Go for file ssytem/cloud storage sence y lipTithe( 3 type(ve2)—_clipLocaton(ve2) Le men cy crate mae atalnhy (yen reign, ite aero =i Sie gee ow ponder ene me Deal Sos “more eg::amaze oe d:\movies: “ ontplar |—>babubhali.mkv_ ‘>For storage purpose instead of Loca leystems (HOD) they use cloud env. ke AWS, SGoogleCtous, iCloud, Azure and etc. (Cloud proves high end. hardware and s/w for companies on rental basis) =>"\" Is escape sequence character in java... it will be useful to void literal meaning certain for characters like '," and etc.. to make them as printable characters... \" elves" \—sives* \\->eives\, ande etc. ‘mysal blob data type are TINYBLOB Upto 255 bytes BLOB Upto.64 Kb MEDIUMBLOB Up to 16 Mb LONGBLOB —Upto4Gb oracle having only blob data type having size upto 4gb JDBC driver and DB s/w indepednet procedure to retrieve BLOB values to DB tables Here we can use either simple statement or oracle DBS] Preparedstatement object, name —|location income photo raja | hyd 9000001 R step1) create Preparedstatement obj having pre-compiled SQL query Preparedstatement ps» con.prepareStatement("SELECT * FROM SHADHI_TAB WHERE REGNC step2) set Query param values.. pssetint,1001) sepa) execute the query / Resultsetrssps.executeQuer); 3 raja yd 900000 (7s | { (inpuststresm) 1 step) get InputStream from ResultSet representing DB table blob col value InputStream isenull; iffrs.next() 1s.getBinaryStream|5} stepS) create OutputSteam pointing new file ‘OutputStream os=new FileOuptustream("new_pictjpg"); step6) copy data of InputStream to outputStream file 1ovtils.copylis.os); Tit is from third party api given apache company jar file name:: commons-ig- jar) (Download from internet) (url https: //munrepository.com/artifact/commons-io/commons-io/2.7) lOUtis is thrid party suplied Utility class to simplify 0 streams related operations... >The class that acts as helper class while doing major operations.. convert 1 form of data to another form data.. copying data and etc. is Utility class. eg: lOUtils , DateUitils, tringUtils, BeanUtils, Arrays and etc. step7) close jdbc objs and streams is.close(); os.close(); rs.close(); ps.close(); con.close(); rnote:: refere PSBLORetrieve java fo insert clob value to DB table column we need set Reader Stream that pointing to text file as Query param value by using ps.setCharacterStreami,-}/ ps.setCharacterstream|--) or ps.setClob(,,,)/ps.setClob(,) methods ‘>For retrieving clob values from DB table col through JOBC ResultSet object us ‘s,getCharacterStream(,) that given Reader object.. To insert pais files, word docs prefer using BLOB cols becoz those file contain both text and images => To Insert text files, csv (ms excel), rich text files prefer using CLOB cols Mysql CLOB data types are TINYTEXT upto 256 bytes ‘oer lOBhaertTenOrecejvecLoBinsertTenteOUjove and TEXT upto 65,535 bytes MEDIUMTEXT upto 16,777,215 bytes LONGTEXT upto 4,294,967,295 bytes Assignment :: develope Profile Mgmt Application to insert PHOTO, RESUME, VIDEO ina single DB table column... Postgresa. s>type :: DB s/w (Light weight) default usernames: postgres ‘=>vendor:: EnterpriseDB password :: root (choose during installation) =>default portno:: 5432 =PAllows to create logical DB , default logical name:: postgres =>Gives PgAdmind/S as built-in GUIDB toot >To download and install : https://www.enterprisedb.com/downloads/post resql-downloads Procedure to create DB table with records in PostgreSQl. using PGadmin tool step) make sure that postgreSQL Db s/w is installed. step2) launch pgadmind/S tool (use start button —> all pres —> posgresql —> pgadmin4/5 —> submit password >.) step3) create Logical DB Fight click on databases ~-> create database —> name ::ntajaddb —> step4) create DB table product ‘expand ntajaiddb-~> expand schemas ~->expand ~>public ~>right click tables~->new 1 product ~> go to colums tab-> add cols. pid inteteger pk (yes) nnfyes) ppname charcter varying 20 price real aty real > ok generated SAL is ‘CREATE TABLE publicproduct tl pid integer NOT NULL, pphame character varying(20) COLLATE pg_catalog."default", price real, ty teal. CONSTRAINT product_pkey PRIMARY KEY (pid) fo insert clob value to DB table column we need set Reader Stream that pointing to text file as Query param value by using ps.setCharacterStreami,-}/ ps.setCharacterstream|--) or ps.setClob(,,,)/ps.setClob(,) methods ‘>For retrieving clob values from DB table col through JOBC ResultSet object us ‘s,getCharacterStream(,) that given Reader object.. To insert pais files, word docs prefer using BLOB cols becoz those file contain both text and images => To Insert text files, csv (ms excel), rich text files prefer using CLOB cols Mysql CLOB data types are TINYTEXT upto 256 bytes ‘oer lOBhaertTenOrecejvecLoBinsertTenteOUjove and TEXT upto 65,535 bytes MEDIUMTEXT upto 16,777,215 bytes LONGTEXT upto 4,294,967,295 bytes develope Profile Mgmt Application to insert PHOTO,RESUME, VIDEO in a single DB table column.. Assignment: Postgresa. s>type :: DB s/w (Light weight) default usernames: postgres ‘=>vendor:: EnterpriseDB password :: root (choose during installation) =>default portno:: 5432 =PAllows to create logical DB , default logical name:: postgres =>Gives PgAdmind/S as built-in GUIDB toot >To download and install : https://www.enterprisedb.com/downloads/post resql-downloads Procedure to create DB table with records in PostgreSQl. using PGadmin tool step) make sure that postgreSQL Db s/w is installed. step2) launch pgadmind/S tool (use start button —> all pres —> posgresql —> pgadmin4/5 —> submit password >.) step3) create Logical DB Fight click on databases ~-> create database —> name ::ntajaddb —> step4) create DB table product ‘expand ntajaiddb-~> expand schemas ~->expand ~>public ~>right click tables~->new 1 product ~> go to colums tab-> add cols. pid inteteger pk (yes) nnfyes) ppname charcter varying 20 price real aty real > ok generated SAL is ‘CREATE TABLE publicproduct tl pid integer NOT NULL, pphame character varying(20) COLLATE pg_catalog."default", price real, ty teal. CONSTRAINT product_pkey PRIMARY KEY (pid) ) stepS) insert records into db table.. scripts —> insert query —> replace values for ? symbols rightclick on product db table ~ ~rerecute query flash symbol- [77 PostgreSQl supplied typed mechanism based jdbc driver s/w for postgresql Db s/w is called postgresql thin driver and its details are river calss name : org.postgresql.Driver jdbc url: jdbe:postgresal (for Local postgresql Db s/w) jdbe:postgresql://:: (for remote postgresql db s/w) Jarfile postgresql-42.2.16.jar (supports auto loading driver class) seperate download from internet ‘munrepository.com (https://mvnrepository.com/artifact/org.postgresal/postgresal/42.2.16) Procedure to develop Java App interacting with PostGreSQl Db s/w {a} keep any old app ready and make sure that its DB table is available in postereSQL 'b) Write the following to create jdbc con object pointing to PostgreSQl Db s/w. I] register jdbc driver 1/Class.forName("org.postgresal.Driver"}; [establish the connection Connection con=DriverManager.getConnection\ "jdbc:postgresal:ntajt1adi “root” abe wrt dbpwd } Change SAL. query as per postereSQl. DB s/w.. ResultSet rssst.executeQuery("SELECT PID, PNAME,PRICE,QTY FROM PRODUCT" 4) add postgresql thin jdbc driver s/w jar file to classpath or build path... right like on the project—>build path—> cfg buildpath —>libraries tab —>add extenal archvies —> browser and select the jar file.. (postgresq)-42.2.16.jar (select from downloaded files location)) ‘e)run the Application nnote:: In Postgresal’s pgadmin take all names like db table name, col names, sequence names and etc..in lowercase.. but infront end App we can them in the SQL queries in any case.. (generally we prefer in upper case) note:: Postgre sql supports sequences i.e we sequence generated value as pk col value while inserting record to db table cols. and the gery sequence looks like this. private static final String INSERT_QUERY="INSERT INTO PRODUCT VALUES(nextval'PID_SEQ’),?,2,2"; (to sequence i generated value) To create sequence in postgresl ur logical DB —>schemas ~ sequences~>create sequence -> name: pid_seq —>definitation tab —> current value :: 1000 , min value U1Generated Quyery ‘CREATE SEQUENCE public. INCREMENT 1 ‘START 1000 MINVALUE 1 MAXVALUE 100000; Assignment:: Develop Apps by choosing postgreSQl.as Db s/w (a) insert Date values (like DOB,DOM,DO) {b) insert blob, clob values ‘Also retive operation (c) calculating age based given person id and his DOB prepare and come fornext class © oracle /mysql PL/SQL procedures and functions = oracle Cursors Sys_refeursor) Gallablestatement object (Its given to call PL/SQL procedure and functions) PL/SQL Procedures/Functions ‘These are named blocks that reside and execute in DB s/w havig block of SQL and Non SQL Statements ..These are like java methods... => PL/SQL procedure does not return a value... where as PL/SQL function returns a value = PL/SQL (PL by SQL) Procedure ot function params will have mode and type 3 modes are 1N—> input (To supply inputs) OUT-> To gather outputs INOUT—> To supply inputs and to gather ouputs in SaLor PL/SQL pl sql logicin oracle OO yisxtx; x —> in param yout param = for assignment pl/sql logic in oracle xxx; > INOUT param. ‘notes: if want 10 results from PL/SQL procedure then we need to take 10 OUT params..To do same thing with PL/SQL function we need to use 9 OUT params and 1 return value, =>PL/SQL programing syntax is specific to each DB s/w.. ‘=> These are also called as Stored Procedures and functions becoz they reside and execute in DB s/w. => Project =>Instead of writing same SQL query in multiple modules [->modules (or Apps, It is recomanded to write in DB s/w only for 1 time I—>Apps {5 PL/SQL procedure or function and use itfrom multiple [->pres. apps or modules having reusability. Ithelps to centralize Persistence logic by keeping in Db s/w with protection (i.e ‘we can hide code from developers) ‘usecasel:: Instead authentication logic, attendent calculation logic in every module , Write it only for1time in Db s/w as PL/SQL Procedure or function and use in multiple modules.. the form of SQL queries the form of PL/SQL procedure and functions Simple PL/SQL procedure/tunctions should be devioped by Programmers direct. where complex procedures and functions will be developed by SQ1/D8 Team. = JDbe Apps use Callablestatement obj to call PL/SQl procedures and functions. v js java Project contains This can be even used to execute static /dynamicSALqueries "|" ur developers (htmlcss,jsjquery angular and pre-compiled SQL queries |—phava Developers (java, servietjp, spring.hb,.) [> SaL developers (SaL, PL/SQL, DBA.) ‘Sample /Example PL/SQL procedure in oracle using SQL Developer if ur full stack developer..u should do all the Tight cick on procedure —> create procedure —> namet:_AIRST-> addls) 3 params 3jobs/roles. x inmumber, yin number 2 out number ‘cloud env.knowlede(awst devops => save (flopy disk) > compile (settings symbol -gear) ‘loud env-knowledelawss evens) . : maven gradle, (CREATE OR REPLACE PROCEDURE P_FIRST XIN. NUMBER, yIN NUMBER, 2 OUT NUMBER) AS Jatin tabefnates, BEGIN a a zx | procedure BS Sparamtype default mode of param "IN" docker and etc. END; name param mode Process to create PL/SQL Procedure’ w ‘hing SQL command propmt / SQL Plus =>open SQL prompt as administrator —>SQL> connect system/manager —> SQL> select * from emp; (some dummany) => ed -> type the the above PL/SQL procedure —> file menu save -> file menu exit—> SQL> / i any compilation error are there —> SQL> show errors; Steps to use Callable Statement obj to call PL/SQL procedure step1) prepare Query having SQL92 syntax to call PL/SQL procedure String query="{ CALL P_FIRSTI?,2,9)" 123 step2)_ Create Callablestatement obj by making the above Query as Pre-compiled SQL query invaslsttement) Callablestatment cs=con.prepareCalllaveryi; java.sql.Preparedstatement() ‘sends the given SQl to DB s/w, makesitas PL/SQL extends procedure or function and returns Callablestatement obj java.sql.callablestatement() having the pre-compiled Sal query. ‘step3) register OUT params with JOBC data types. cs.registerOutParameter(3, Types INTEGE JDBC data types are bridge data types b/w java data types and SQL Data types they are useful to give instructions to JDBC driver to param jdbedatatype Conver java notation data to Sal notation data and vice-versa, index java datatype jdbc type ‘sQL data type (oracle) stepd) set values to IN params ine csten Jeep saheete we MetaData/Metalnfo speaks about either gathering info or passing info about existing data/info. => JDBC MetaData is about gathering more info about underlying DB s/w representing jdbc con obj... and underlying DB table reprsented by ResultSet object.. underlying query params(?) represented by PreparedStatemet or Callablestatement objs types of IDBC MetaData:: a) DatabaseMetaData (To know limitations and capabilities underlying DB s/w) b) ResultSetMetaData (To get More info Db table that is represented by ResultSet obj) )ParameterMetaData_ (most of jdbc drivers not supporting this feature) DatabaseMetaData Gives imitations and capabilities of underlying Db s/w represnted by jdbe con obj =>To create this object DatabaseMetaData dbmd=con.getMetaDatal); we can call 50+ methods on this object to get more info underling DB s/w.. Some methods are? smantength) _getnaxcolunnssncroupby() etaxcolumnetotndex) refer DatabaseMetaDataTestjava ettaxcolumeznorderty() _getnaxcolunnstnselect() _getvancolonnsrnTab16() _gettaxconnections() otnaxcursornonatensth() anid ete ‘DatabaseMetaData means itis the obj of undelying JDBC driver s/w supplied java class that implements java.sql.DatabaseMetaDatal!) notes: The values given by DatabaseMetaData object will change based on the DB s/w and jdbc driver we use.. =>if any method of JDBC MetaData programming is giving 0 oF 0.0 oF null. that is not correct info about DB or table or param.. that indicates the underlying JDBC driver can not gather that info.. => Realtime usecases of DatabaseMetaData :: ‘Will be used in the development of GUIDb tools like SAL developer, mysql workbench ,sql yog and ete. ResultSetMetData ented = Gives more info about Db table like (col names, col types other details about cols) repr IDBC ResultSet object =>ResultSetMetaData meansit isthe object of java class that implements java.sql.ResultsetMetaData(!) =>To create ResultSetMetaData object ResultSet rs=st.executeQuery("SELECT * FROM STUDENT” ResultSetMetaData rsmdsrs.getMetaDatal); => we can invoke 20+ methods on “rsmal” object to know more about Db table represented by ResultSet object (rs) string. sgetcataloguane( int coluen) Gets the designated cours table’ catalog name, string getcolumnciasstane(int colum) Retums the fuly-quatfed name of the Java cass whose instances are manufacture the Resultet.getObject Is called 0 reove a vale fm he column, nt etcoluancount() Fetus te numer of cours nis nesultset objec. sot setcolunnossplaysize(int colutn) Inciates the designated colunn’s normal maximum with in characters string. igetcolumntabel (int column) Gets the designate column's suggested tte for use printouts and cspays. string sgetcolummane( iat coluen) Get the designated cours name nt ketcolummtype(int coluen) Retrieves he designated column's SOL ype string igetcolummtypensne int colin) Retrieves the designcted column's database-specic ype name, nt setPrectsson(int colusn) (Get the designated column's epactiad column size. aot sgetscale(int colum) {Gets the designate column's number ois to right the decimal point ResultSetMetaData is very useful while generating reports and while developing GUIDB tools. Refer ResultSetMEtaDataTest java 101 raja hyd 90.55 102 ravi vizag 91.55 103 suresh delhi 87.55 ere ReslsetMetaDsta ob ResutSetMetaData smal; iestena rsmdars.getMetabatal, Ine countet: smal ( ‘ountersmd.getColumncount) ori cl names for(i =asecountt) ‘Shatemout.pintrsmd.getColumabel ‘Spetemout pit ‘rit cl datatypes for(int =tgecounte) ‘Shatemout.pintrsmd.getColumaTypeNametie” systemout. prints vine oug-—> nurmber(102) precision 10 lec elena) vase ‘welt 20058 Torintnasescounte { ‘otal length precision (10) ‘Shatemout. print getstrinet +" sale? > Syctem.out.printn Joa uwnie serine more nfo about tables forint ict-eramd.gettolumncount)+ ( ‘Systemout pine index = Sytem. print col name aed getColrnlabel ‘System.outprimin(co data typename" 4smd-gtColumnTypelamel ‘Systemoutrimincl sale 4rsmagetsall ‘Allows togather more info about parameters () tat inthe SQL. query represented by the JDBC PreparedSatement or CallableStatement object = Most ofthe ji river not supporting thi concept {or this inertace "ParamaterMatsbota"- its the bjectofunderving JDBC driver s/w supplied java class that implements avasql.ParameterMetaDatal!) ‘To create this object PreparedStatement ps con preparestatement("Insert into Student values(2,2,22)") ParameterMetaData pmdeps.getParameterMataDstal we caninvoke methods on “pra” object to get more info parameters(). Moaitier and Type Metnod and Deseripion string tetParaneterclasshane(Int paran) Retrieves the uly.qaliieg name of the Java class whose instances shel be pased tothe method Preparedstatenent.setobject sat setParanetercount() Retrieves the numberof parameters in the Preparedstatenent objet er which this Paranete fontains ivormaton int xtraranetertode(int paran) Retrioves the designated parameters mode. st etParanetertype( int paras) Retrieves the designated parameters SOL ype. string stParanetertypetiane(int paran) Retrieves the designated parameters database-speife ype name. int etPrecision(int paron) Retroves the designated parameters specied column size ant setseale(nt paran) Retrieves the designated paramete's numberof cst ght of he decimal point, sont ‘shud Lable(int parae) Retrieves whether nul valves ae aowed inthe designated parameter. boolean sessgned(int param) try(Preparedstatement psxcon.prepareStatement{GET_ALL_STUDENTS_QUERYIM. IIereate ParameterMetaData object ParameterMetaData pmd=null, if{pstenuil) This code will give exception... becoz All popular pmd=ps.getParameterMetaData(); JDBC driver s/ws are not supporting this Iiget more info about parameters ParameterMetaDAla...concepts.. int count-pmd.getParameterCount(}; java.sql.SQLException: Unsupported feature ‘System.out.printin(count); forlintintjieecount+){ ‘System.out.printin(" ‘System.out.printin(’ system.out.pentla 2 "'4pmd.getParameterTypeName()} System.out.peintin(” System. out printin( "parameter precision: wit jarameter scale :2"+pmd.getScale()} “spmd.getPrecision(i}; Wireya Working with Properties fle ‘>The tet file that maintains the entries inthe form of key-value pairs is called properties fie We can gve any extension to properties file. but the recomanded extension “properties velGrulaNs java.util Hashtable (any objs as keys, values, ‘Personal information -comipent owends * chelements) penons-tot Imvautttropertes (Map collection) pperson.addrs=hyd {Only String obs as keymraues /—brops [obi of java.util, Properties) personié | 01 ° personnane| rela 1 personedra| vd , keys values ering) (String Logic to copy Properties file info to java.util.Properties case Sh ‘//Locate properties file. InputStream is=new FileInputStream("src/com/nt/commons/pesonallnfo.properties"); ‘/[create java.util. Properties object Properties props=new Properties(); ‘//Load from file (Performs the actual ast) So.plpros); S.o.p(" person.name key value is::"*props.getProperty("person.name")}; //raja, S.o.p("person id ::"+props.getProperty("personid")};// 101 Collecting jdbe properties from PRoeprties file note:: The slogan in the software industry i. Do not hardcode inputs in ur App source code thet are changable Inthe future, Ty collect such values tothe Application from outside the Application... by taking the support of Aitferent options ike properties file or xml file or cmdline args os system properties o steams lke Scanner and Gattcoing = jibe driver cass name, jab ur , db username, db pwd and et. are called jdbe properties. these values change based on tbe diver and DB s/w we use... itisrecomanded not hardcode in our App source code.. collect them from outside the application using the one ofthe softcoding techniques. (Generally we prefere properties fle (standalone App) and xm fle (web.xml) in web applications) Use casei: while moving the project from Dev Env..to Testenv.to UAT env... Prod env.. The jdbe properties wil change env toe. becor DB detalls or driver detalls will change env..to env. So better take the suppor of softcoing to supply jdbc Droperties tothe Application. + et fet = Appt /projt Prod Env (oracle Ob s/w, “race thin ve) Test Ew (mysq 08 s/w Unt tov (pores Oba ev Env (mysq DB s/w ‘connector/ Driver) postresjdbe iver Connector/ river) (dousername, PL eaceaanain password, ul info changed) FOCUS = Focus on One Course Until uSucceded saberroja Jose Refor_SolectTestaWithPropertosFleTest java [>comntcommons a knowlege growth = Vertical Growth |—>dbe properties |—>com.nt abe orizontal growth >< | SelectTestswithProperiestleTest java ‘verte 6 Example code Tinunstam/ynnens : a woceninaltios | Ge) CD iiastoon = fidbe.driverscom.mysql.cjjdbe.Driver fidbe.urlejdbe:mysql:///ntajsiadb Hdbwuser=root db. pwd-root db Aop place code this code to collection jdbc properties from properties file and to create jdbc con oblect /Moad the properties file Into to java.util. Propertie class object InputStream is=new Filelnputstream("src/com/nt/commons/jdbe.properties! Properties props=new Properties(}; props.load{is); register idbc driver s/w (optonal) Class.forNametprops.getProperty|"jdbe.driver")}; [establish the connection ‘Connection con=DriverManager.getConnection(props.getProperty("idbc.r), propsgetDroperty-abaiser), Props.getProperty("db.pwa); Batch Processing /Batch Updation "© Ina normal JOBC App to send and to execute “n” SQL Queries to DB s/w we need to use "ni" roundtrips b/w Java App and DB s/w Le we need to use network for 2*n times... some iis very corti. ‘>To overcome the abpvce problem keep multiple related SQL queries in a batch and send batch to Db s/w. ‘execute the queries%batch in DB s/w and gather query results as batch of results back to DB s/w. Itust uses ‘one network roundtrip (2° 1=2 times network) to dealwith batch of “ni SQL. queries, Java App (without batch cessing) query Wer eAR | geen ery rea] ‘query rose iva App ‘do everthing or nothing principle Le thoguh one query execution filed inthe bateh, the remaining SQL queries il stil execute note:; We can add only nonselect Queties tothe batch. Le Select SQL ‘queries can not be placed ‘Sample code using simple statememnt object ‘Statement stecon.createStatement); [adding queries tothe batch Like this we can ada StadaBatch("insert into student values(101"aa'/hyd90)"};_ | multiple nonselect Sal Queries staddBatch("inert into student values(102"ajesh’hyd80)"); | either dealing wth same db table staddtatch( "update student set sadd"hyd where sna>~100"); | oF diferent db table staddBatch( "delete from student where sno>=1000"); Lexecate the batch sends batch of Sak queso OB s/w, executes them in Obs Ine reeul(ostexecteBateh); | eo 7 ~ ‘bring their results a batch nthe form of int] result) process the resus sesult] ‘o_ BatchProcessing does not perform “do ever thing or + nothing principle” based Query execution. if want to apply 3 that then go for TxMgmt onthe top of bate results. Sopl*no.of records that are effected “staal; //ves S Canon diterentexeetl) method of bc 9? na) execteQuen{) Forse SL queie ereaevpsstet) = | (gor nonselect at ques) srectatargeudste) =| seers excite) For both select nd romasact ies and ao for cling PSO proceresfunctions ecuebateh Forth procesing (Q) Why we can not add select SQL queries to batch of Batch Processing"? ‘Ans) The return type of executeBtch() method Is int Le it can not hold the select SAL query generated 1S object ..So we cannot add select SOL queries to batch ofthe BatchProcessing/Updation sic then how to execute group of select queries? ‘Ans) Not posbi ‘>The Process of combining related operations into single unit and executing them by applying do everything or noting principe Is called TaMigmi{Transaction Management) ‘usecarer 1. traneferMoney operations (withdraw amt from source account, deposite amount into dest account) neads Tamgmt 2. Employee Registraton( insert record in table, insert record finance Db table) needs Tx mgmt atch Processing does not support TxMgmt by default. we need to add addtional logics onthe top BatchProcessing '2) sable auto commit on Db s/w (con.setAutocommi{fabe)) ~>default tue.. 'b) Write adational on the result] of executeBatch to commit or rollback Tx boolean fagtase; forlinti0;iresult length HAI ‘result ==0}¢ ‘Why commit) or rlibck|) are given on “con” object, why not flags, i statetement object break; Instat eject? » ns) Since we execute different SQL Queries using diferent ) STatementobjs In order to commit or rollback al these queries iWiagearuey. related Taste in single short they have given con.commit() a and con.ollsack() methods in connection obj who creates Pe eremeeiaiatenaa allies ‘multiple statement objects. set concommit(; {/eommit Te TCL y ‘DeMgme Code 2) Begin Tx r nD ‘TransferMoney Operation Having JObe TxMgmt b) execute logies/queries Deable UDBC_ACCOUNT) genta fer eh roan Iden fcno(pk)holdername balance ~>based on the results of batch processing/updation ‘we can cal con.commit} /eon.olback() method 101 rb ‘30000 a2 ony ‘80000 refer TeMgmt_TransferMoneyTestjava ‘=o not use try with resource while working TxMgmt becot..oing Intry with resource con ob willbe closed at ) the end of try bloc. 50 calngcon.comimit() or con liback|) cateh(excepton e ‘rows exception ~ try(Connectioncons0M.getConnecton(s finally’ chek cond Heon.commit) or con.rllback() ) ; Not at all good cateh(Exetion of ? ‘Teon commit) or con rollback) not posible here. LUstcstring>Hat=new ArrayList) ;//bad_//gives mutable object LUstestring>Hst= Uist of 11208 ive immitable obejet [trom javad (Wot best in all eases) ener toate ope stanton) eee tetera = : centr weet matt tt en Shee act ‘srRowsetis extension of ResultSet to ho bunch of ecords ven by select SL query" exection ver Rowse objects the abjectot java lass that implements jovaxseh tse) extends java st ast (el Resutet abject are connected objects Le we can nt docline Onta manipulation th ut having connec with sf (0) Does not support Bean tye Programming (Programming with str [getter methods) {6} oer not spport event handing [G)Rerutset ob are not Seralzale abject: Lawe can not end them over the network. ‘To overcome these imitations we can use RowSete andadvatantges ae (0) we can gpl ai functionality of Reset objet (6)** these alscomnected objects Le we can modtyRowSets oben ofine mode with out having conection with Ob sf and we make there modifications reflecting b/w once “Connections bck (a)suppors bean style porsaming (a) Supports event handing. (The action doe one record ofRowSet canbe made reflecting on ther record) {e)Moseofthe Rowse bj are SerilinabeobS0they canbe set ovr the network. Stypesot owsets ae there ‘s}08cRowset 1) cachedRowset** €) WebRowset 1 toinowset 1) FiteredRowset : Frvmeagh Rowse) JvoxsalrowsetdcRowset) vassal cows CachedRowsSet (acl thin/oi driver ging clases supporting entends types Rowse voxsalrowset WebRowset() 1LoradeldbeRowsete) implements be ows) ‘tends 2oraceCarhedRowset( implements CachedhowSe() “oreceWebsowsete) implements Webowset axsaltobsetJoinRowseti) jana rowset.eredRowSetl ‘Aorecelcinowsete) implements Jainfowset) ‘Soraceiteredhowset) implements Fiteredowset) ' ‘Mow restvict noo cords That should come RS or Rowset though ‘iis connected Rowse objet 1s select SOL querys ging more records? Sisnotasarilznbe object, Dns) fstaetFetcszlal or ronselsetetchszet) meethods are Siti ghenin RowSet to work ike ResuSet not wortingin moto the DBC drivers. x eemete we an Supports Bean sie proramming he stsctodous[)orrowaetaettons(n) metho does nat support fine data manipulation “StheceRoweets are defouitscolable “ue can ace Senate orient BahavourIdbcRowSet. “> These Rowse ar Read Ory Rowsets by default 2nd we can not make ther ‘sUpdetabeRowsts in any ange oa ‘eaten onan aeons eictonsereio ‘eth once Hi [scetteanord st ing son ganas geile he mason ane fine not hag cancion tO cab ten ‘etter ging omen by ety aeepchanges) mate ‘ite devin FOR Pees aA heb appt) hte ‘ona ver pm, ‘eitpar every boy marae agent Ta, an Mtg mle bade. catatonia Try OracleCacedRowsetcownet=new OreeCochedRowSet() ‘ater cartons ised propetes ‘rowzetetUe(Hocoradethin @locahost 526" “rouse atUrernamel ten ‘rowsetsetassworal anager, eet sO. dey ‘rowsetsetCommand'sELECT sNO SNAME,SADO AVG FROM STUDENT Heroweetsstrertowsi, “esac the sh ery rowenta) “orcars the Rowset ‘rowset.eteadOnifale) hieerowsetnest ‘Sptem.outprintincowsetgeti}e™ “srowset gesting “rere. getsrng(s}e" “sonst gtroat S09 8 5) romsetabsoltlt ‘romsetpaetesting!3newyor" “romsstadateRow)//This scaled ofine/daconnected date processing ee a Theeadalep(4000), orocss the Rowset ‘romsetceentchangeh ‘whlefronsetaet( )_ Smematrin cow gt “scot geting “serowse getstring}" “sero gloat); “Vinyasa in Soup Based WebService whare data wil be cain the frm of en i not ae ree tome ac rete: tedvarecgot cling teibng staring bac ies onde con ab send ‘saa over me nietataia neg Palomo undone sler Webhowsetestiova ‘nfOradeWebRowset wrowzstenew OraleWebRowSet) “sso propeties ‘rows et dc oraletin:Olocalnoss1S21:40) varowset setsermame sym \erowsetsetassworal manage Thatsat very \wrowset setCommand SELECT SNO SNAME.SADO,AVG FROM STUDENT, Twrowetsstaxtowslt esac to SAL query Torocss tne Rowset tirowset etResdOnile); ‘eiefwrowsetnet 1 Semovtrminoonsetgnie “sows etn” “arose gettings snows gto Systemoutprint"Weting RowSet objet data to Ke Iorteto xm ie Water writerenew Fete student infos ‘wrowsetnrtatoriters Systemoutpti"Wrling RowSet objet data onthe console nx format" rowaetrtedlystmut, Yh fateh SabExeption eprint > atefbeeption ‘sprimstackraclh ’ ows to combine mutipeRowsets it ingle Rowse by epphing SOL inerjolns ew OracleCachesRowset (OraclecachedRowsetr=?=new OracleCachedRowset) ‘Oratlecinowset owset-new OraeoinRowsetl ‘aeiaetUelcbeorsdathin@locsinont iS? ‘celaetParaword manage ‘celaetMatencotumos {sisetCommand SELECT EMPNO,ENAMEO8 SAL,DEPTNO FROM EMP, etanestl eszsetuabcoracetinelcahostas2ia%e" eee eszsetUsernamel ster") ‘ezactPaeawordt manage ‘cezastatcnolum) “Gs2set Commend SELECT DEPTNO.ONAME LOC FROM DEPT“: ‘cnzanecitel oroces the itouset ‘ieetonset net ( ‘tesatenception ole: insted of working wit SooRowets beter tse Seprisicktrace) 51 avery thins => lows to ter the record that shuld come to Rowse based on ja code based condtons. “Shs Condon witbe prepared as Predicate objet nothing but clss that s implementing Prediatel) and we wre conditional loge inthe evaluate] metho -> Forevery record this evluate() method erectefthismethou returns tre then ‘record willbe therein FiteredRowSet otherwise wl nt be there in FteredRowSet trample code AnyfOraleiteredRowSe fnew OrceiteredRowset er Tezsete socoradeshine@locathort 52136" fersetUseramel'sytem"h feesetPassworal"manaserh {ee.etCommand'sE LECT EMPNO;NANIEJOB.SA.DEPTNOFROM EMP"; fee aet ere Fite ANS Weevecitel roca rowset ‘wets ‘Shtem.out print getintto” “Wie gstnga)” “elgetsting3}" “ffgetsloa(e affgetnt: ’ 1 ‘etesatexcepton sl Seritstockrocl: 1 Mymsin rvate static cass iter implements Predict, Privat String cotame; ria String condte; 1/sishit 0 > generates contraction uli Fiteristring olan, String cond) ( Soverise Puli bonean evans )( ‘itemaut print iteresRowSetDemo Fiter.evalste wt sing olvalscrsgetstringcoNomel, return false ) ‘atscutaception se seaitacracli retwn ase override Puli booleonevluteObjet sve nt our) throws SOUERepton{ 117000 Astogeneated method stub returns , override Puli boolean evaluate Objet ae String aturaare] throws SOUException 7/1000 ht-generatedmetiod st ‘ote: ts beter condtion dec in the SAL query self instead ‘woking with FiteredRowoet hein coiton oe code. Flow: when frsnentf metho is clled, each record given Select Query of" goes to ‘vaste as Rowse bj there rad given "ename” caval and check against. en condtion dat and return true/false ue then keeps the recordin "ts otherwise Iewltnot kee. (rs oFterered Rowset) ‘notes Indurry we CachedRowSet and WebRowSe in roe. => Mis the factory that contains set fread avila con obs belore cust bring used. lternt ype of OBC con poole “oo standalone App Sever Managed Ib conpook oewtlin standalone ‘Serested nd mangedby webSerer op serve ike m serenade osceoec? | Sah je diver) Se ea my ‘s>Datasource ob ats entry pont for con poke to rete con bi indecon poo! Roget con objects rom bc eon pool werneed Detasource objet sabe isthe object fave class thatinpemetns jivnesalDetasouree ‘Connection cons getComneton) I=>Gves one con objet rom be con oot Two yper etna con 3} iret 18 com object “zceated bythe programmer manvally ‘Connection con-Oriver Manager etConneton 1) Posted 08 con objet "Gathered rom IDC con pool sng Datsoure object Connection cones etConnetion racleDstsoureeConnactonPool deenew OraleComnatonPoolbstaSourcell “sstURUjbcoraethne@locatnos 152130" (ssetuser stem, ‘ssetPesword- manage" se llthese details and creates secon pol hong itl 8 be cn beat) et posted ide con ob onmdngetConnection); ere Statement bi Statement steconcreteStatement; serdand erecta SOL. query eset snceve SECT SN SNAMESADD AVS FROMSTUDE: Horoces teks ‘aes ‘temo enti getns}+" “se gtSingla}e"“sngettring( I+" “tego Uwe refer PoledConnTar ova Tomeatatbloge ana et. wil be esrnaain set rameworks)

You might also like