You are on page 1of 3

Assignment 5: JDBC 3.Write a Java program which does the following: 1. Ta es as first line of inp!t" a parametri#ed $%& '!

er(" and s!)se'!ent lines containing val!es for the parameters* (o! can ass!me that each + in the $%& '!er( viewed as a string represents a parameter val!e. ,. -.ec!te the parametri#ed $%& '!er(" and o!tp!t its res!lt with one line per row in the res!lt" along with a header containing the names of col!mns. /se the ta) character to separate col!mns 3. 0ote: 1o! can ass!me that what is inp!t is a '!er(" not an !pdate. Co!nt the n!m)er of + characters in the '!er( string to fig!re o!t the n!m)er of parameters. Don2t worr( a)o!t datat(pes" 3!st !se set$tring45 to set parameter val!es" and get$tring45 to get res!ltset attri)!te val!es. import 3ava.io.6* import 3ava.s'l.6* p!)lic class test 7 p!)lic static void main4$tring args8957 ::load Drivers tr( 7 Class.for0ame4;org.postgres'l.Driver;5* $(stem.o!t.println4;Driver &oaded s!ccessf!lll(;5* < catch 4Class0ot=o!nd-.ception e5 7 e.print$tac Trace45* < Connection con* tr( 7 con > Driver?anager.getConnection 4;3d)c:postgres'l:::localhost:d)ms,@13;";hiral;";)ha,1hir15;5* $(stem.o!t.println4;Connected s!ccessf!lll(;5* Arepared$tatement pstmt > n!ll* Bes!lt$et?etaData rs * tr( 7 B!fferedBeader )r>new B!fferedBeader 4new Cnp!t$treamBeader4$(stem.in55* $(stem.o!t.println4;-nter a '!er( on first line and its parameter val!e on second line:;5* $tring &ine > )r.read&ine45* $tring89 data > new $tring81@9* int i >@* :: Cnp!ts while4D&ine.e'!als4;-.it;557 data8iEE9 > &ine* &ine > )r.read&ine45*

< pstmt > con.prepare$tatement4data8@95* for4int >1* Fi* EE57 pstmt.set$tring4 " data8 95* < :: ?eta Data rs > 4Bes!lt$et?etaData5 pstmt.get?etaData45* int colCo!nt > rs.getCol!mnCo!nt45* for4int l > 1 * l F> colCo!nt*lEE 57 $(stem.o!t.print4rs.getCol!mn0ame4l5E; GHt;5* < $(stem.o!t.print4;Hn;5* $(stem.o!t.print4;>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>Hn;5* Bes!lt$et rs1 > pstmt.e.ec!te%!er(45* :: Bes!lts while4rs1.ne.t4557 for4int l > 1 * l F> colCo!nt*lEE 57 $(stem.o!t.print4rs1.get$tring4l5E; GHt;5* < $(stem.o!t.print4;Hn;5* < :: Closing pstmt.close45* rs1.close45* < catch 4$%&-.ception s'le5 7 $(stem.o!t.println4s'le5* $(stem.e.it415* < catch 4CI-.ception e5 7 :: TIDI A!toJgenerated catch )loc e.print$tac Trace45* <

pstmt.close45* con.close45* < catch 4$%&-.ception e5 7 :: TIDI A!toJgenerated catch )loc e.print$tac Trace45* <

<

<

You might also like