JDBC	              Jussi	  Pohjolainen	  Tampere	  University	  of	  Applied	  Sciences	  
JDBC	  Intro	  •  Java	  Database	  Connec@vity	  in	  Java	  since	  1.1	  •  API	  in	  Java	  for	  accessing	  Databas...
Drivers	  •  To	  access	  a	  database,	  you	  need	  a	  driver	  •  To	  code	  in	  Java	  is	  always	  the	  same,	...
Driver	  Types	  •  JDBC	  Drivers	  are	  divided	  into	  four	  categories	       –  Type	  1	  that	  calls	  na@ve	  ...
To	  use	  JDBC	  1.    Register	  driver	  2.    Access	  database	  3.    Do	  some	  SQL	  magic	  4.    Handle	  resul...
1.	  Register	  the	  Driver	  try {    // The driver string here is given you by the    // driver documentation.    Class...
2.	  Connect	  to	  Database	  try {    Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver");    Connection conn = DriverManager...
3.	  Some	  SQL	  Magic	  try {    Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver");    Connection conn = DriverManager.getC...
5.	  Close	  connec@on	  try {    Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver");    Connection conn = DriverManager.getCo...
Handle	  Result?	  •  In	  previous	  example,	  the	  result	  of	  the	  SQL	  was	     boolean	  value	  (we	  did	  no...
4.	  Handling	  Results	  try {    Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver");    Connection conn = DriverManager.getC...
ResultSet	  rs.next();	  rs.next();	  rs.next();	  //	  Prints	  “Williams”	  System.out.println(rs.getString(“Last	  Name...
ResultSetMetaData	  •  Don’t	  know	  column	  names?	  Or	  amount?	  •  You	  can	  check	  these	  using	  ResultSetMet...
Transac@ons	  •  If	  you	  want	  to	  commit	  several	  sql	  –	  commands	     into	  one:	      –  conn.setAutoCommit...
Prepared	  Statements	  •  Prepared	  statement	  or	  parameterized	     statement	  is	  a	  feature	  used	  to	  execu...
Scrollable	  Resultset	  Statement stmt =con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,                    ResultS...
Values	  •  TYPE_FORWARD_ONLY	  (default)	  •  TYPE_SCROLL_INSENSITIVE	  •  TYPE_SCROLL_SENSITIVE	  –	  all	  updates	    ...
Methods	  for	  Scrollable	  ResultSet	  •    next()	  •    previous()	  •    beforeFirst()	  •    aierLast()	  •    absol...
Update	  Result	  •  It’s	  possible	  to	  update	  the	  result	  using	     methods	      –  updateString()	      –  up...
Update	  while(rs.next()){       System.out.println(rs.getString("Firstname"));}rs.previous();rs.updateString("Firstname",...
Adding	  a	  Row	  rs.moveToInsertRow();rs.updateString("firstname", "Jack");rs.updateString("lastname", "Smith");rs.updat...
Dele@ng	  a	  Row	  •  rs.last();•  rs.deleteRow();	  
Upcoming SlideShare
Loading in...5
×

Java JDBC

841

Published on

Published in: Technology
0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
841
On Slideshare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
44
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide

Java JDBC

  1. 1. JDBC   Jussi  Pohjolainen  Tampere  University  of  Applied  Sciences  
  2. 2. JDBC  Intro  •  Java  Database  Connec@vity  in  Java  since  1.1  •  API  in  Java  for  accessing  Databases  •  PlaDorm  independent,  Database  independent  
  3. 3. Drivers  •  To  access  a  database,  you  need  a  driver  •  To  code  in  Java  is  always  the  same,  changing   the  driver  changes  the  connec@on  to  different   database.  •  Lot’s  of  drivers  for  different  databases:   MySQL,  Text,  MS  SQL  Server..  
  4. 4. Driver  Types  •  JDBC  Drivers  are  divided  into  four  categories   –  Type  1  that  calls  na@ve  code  of  the  locally  available  ODBC   driver.   –  Type  2  that  calls  database  vendor  na.ve  library  on  a  client  side.     –  Type  3,  the  pure-­‐java  driver  that  talks  with  the  server-­‐side   middleware  that  then  talks  to  database.   –  Type  4,  the  pure-­‐java  driver  that  uses  database  na@ve  protocol.    •  In  most  cases  you  can  access  the  same  database  with  four   different  type  of  drivers  •  List  of  drivers:   –  hQp://developers.sun.com/product/jdbc/drivers  
  5. 5. To  use  JDBC  1.  Register  driver  2.  Access  database  3.  Do  some  SQL  magic  4.  Handle  result  5.  Close  the  connec@on  
  6. 6. 1.  Register  the  Driver  try { // The driver string here is given you by the // driver documentation. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");}catch(ClassNotFoundException e) { System.out.println(”Can’t find the driver!");}
  7. 7. 2.  Connect  to  Database  try { Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver"); Connection conn = DriverManager.getConnection( "jdbc:odbc:mydatabasename", ”userlogin", ”password");}catch(SQLException e) {}catch(ClassNotFoundException e) {}
  8. 8. 3.  Some  SQL  Magic  try { Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver"); Connection conn = DriverManager.getConnection( "jdbc:odbc:mydatabasename", ”userlogin", ”password"); Statement statement = conn.createStatement(); statement.executeUpdate("DELETE FROM employees WHERE id<20");}catch(SQLException e) { }catch(ClassNotFoundException e) { }
  9. 9. 5.  Close  connec@on  try { Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver"); Connection conn = DriverManager.getConnection( "jdbc:odbc:mydatabasename", ”userlogin", ”password"); Statement statement = conn.createStatement(); statement.executeUpdate("DELETE FROM employees WHERE id<20"); statement.close(); conn.close();}catch(SQLException e) { }catch(ClassNotFoundException e) { }
  10. 10. Handle  Result?  •  In  previous  example,  the  result  of  the  SQL  was   boolean  value  (we  did  not  handle  it).  •  If  SQL  is  select,  then  you  can  retrieve  the   results  •  Use  ResultSet  object.  ResultSet  holds  the   result  of  your  SQL  query  •  You  can  navigate  in  result  set  
  11. 11. 4.  Handling  Results  try { Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver"); Connection conn = DriverManager.getConnection( "jdbc:odbc:mydatabasename", ”userlogin", ”password"); Statement statement = conn.createStatement(); ResultSet rs = statement.executeQuery("SELECT * FROM employees"); while(rs.next()) { System.out.println(rs.getString("someColumn")); } statement.close(); conn.close();}catch(SQLException e) {}catch(ClassNotFoundException e) {}
  12. 12. ResultSet  rs.next();  rs.next();  rs.next();  //  Prints  “Williams”  System.out.println(rs.getString(“Last  Name”));  
  13. 13. ResultSetMetaData  •  Don’t  know  column  names?  Or  amount?  •  You  can  check  these  using  ResultSetMetaData  •  Example  usage:       ResultSetMetaData rsmd = rs.getMetaData(); int numCols = rsmd.getColumnCount (); while (rs.next()) { for (int i=1; i<=numCols; i++) { System.out.println(rs.getString(i)); } }
  14. 14. Transac@ons  •  If  you  want  to  commit  several  sql  –  commands   into  one:   –  conn.setAutoCommit(false); –  // do some sql –  conn.commit(); –  conn.rollback();
  15. 15. Prepared  Statements  •  Prepared  statement  or  parameterized   statement  is  a  feature  used  to  execute  the  same   or  similar  database  statements  repeatedly  with   high  efficiency.  •  Example   Connection con = connect(); String sql = "UPDATE table1 set one = ?, two = ?"; PreparedStatement preStmt = con.prepareStatement(sql); preStmt.setInt(1, 123); preStmt.setString(2, "myNewValue2"); preStmt.executeUpdate();
  16. 16. Scrollable  Resultset  Statement stmt =con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);ResultSet srs = stmt.executeQuery(SQLQuery);
  17. 17. Values  •  TYPE_FORWARD_ONLY  (default)  •  TYPE_SCROLL_INSENSITIVE  •  TYPE_SCROLL_SENSITIVE  –  all  updates   happens  immediately  •  CONCUR_READONLY  •  CONCUR_UPDATABLE  
  18. 18. Methods  for  Scrollable  ResultSet  •  next()  •  previous()  •  beforeFirst()  •  aierLast()  •  absolute(int  x)  
  19. 19. Update  Result  •  It’s  possible  to  update  the  result  using   methods   –  updateString()   –  updateInt()   –  updateFloat()..  •  Once  updated,  call  updateRow(),  which  will   move  the  result  to  database  
  20. 20. Update  while(rs.next()){ System.out.println(rs.getString("Firstname"));}rs.previous();rs.updateString("Firstname", args[0]);rs.updateRow();
  21. 21. Adding  a  Row  rs.moveToInsertRow();rs.updateString("firstname", "Jack");rs.updateString("lastname", "Smith");rs.updateInt("idnumber", 20);rs.insertRow();
  22. 22. Dele@ng  a  Row  •  rs.last();•  rs.deleteRow();  
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×