SlideShare a Scribd company logo
JDBC	
  

            Jussi	
  Pohjolainen	
  
Tampere	
  University	
  of	
  Applied	
  Sciences	
  
JDBC	
  Intro	
  
•  Java	
  Database	
  Connec@vity	
  in	
  Java	
  since	
  1.1	
  
•  API	
  in	
  Java	
  for	
  accessing	
  Databases	
  
•  PlaDorm	
  independent,	
  Database	
  independent	
  
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..	
  
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	
  
To	
  use	
  JDBC	
  
1.    Register	
  driver	
  
2.    Access	
  database	
  
3.    Do	
  some	
  SQL	
  magic	
  
4.    Handle	
  result	
  
5.    Close	
  the	
  connec@on	
  
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!");
}
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) {

}
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) { }
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) { }
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	
  
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) {

}
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	
  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));
         }
     }
Transac@ons	
  
•  If	
  you	
  want	
  to	
  commit	
  several	
  sql	
  –	
  commands	
  
   into	
  one:	
  
    –  conn.setAutoCommit(false);
    –  // do some sql
    –  conn.commit();
    –  conn.rollback();
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();
Scrollable	
  Resultset	
  
Statement stmt =
con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
                    ResultSet.CONCUR_READ_ONLY);

ResultSet srs = stmt.executeQuery(SQLQuery);
Values	
  
•  TYPE_FORWARD_ONLY	
  (default)	
  
•  TYPE_SCROLL_INSENSITIVE	
  
•  TYPE_SCROLL_SENSITIVE	
  –	
  all	
  updates	
  
   happens	
  immediately	
  
•  CONCUR_READONLY	
  
•  CONCUR_UPDATABLE	
  
Methods	
  for	
  Scrollable	
  ResultSet	
  
•    next()	
  
•    previous()	
  
•    beforeFirst()	
  
•    aierLast()	
  
•    absolute(int	
  x)	
  
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	
  
Update	
  
while(rs.next()){
       System.out.println(rs.getString("Firstname"));
}

rs.previous();
rs.updateString("Firstname", args[0]);
rs.updateRow();
Adding	
  a	
  Row	
  
rs.moveToInsertRow();
rs.updateString("firstname", "Jack");
rs.updateString("lastname", "Smith");
rs.updateInt("idnumber", 20);
rs.insertRow();
Dele@ng	
  a	
  Row	
  
•  rs.last();
•  rs.deleteRow();
	
  

More Related Content

PPT
Xml parsers
PPTX
Black Hat: XML Out-Of-Band Data Retrieval
PPTX
Java file
PDF
Jdom how it works & how it opened the java process
PPT
Jstl Guide
PPTX
Rebuilding Solr 6 examples - layer by layer (LuceneSolrRevolution 2016)
PDF
Life outside WO
PDF
ERRest: the Basics
Xml parsers
Black Hat: XML Out-Of-Band Data Retrieval
Java file
Jdom how it works & how it opened the java process
Jstl Guide
Rebuilding Solr 6 examples - layer by layer (LuceneSolrRevolution 2016)
Life outside WO
ERRest: the Basics

What's hot (18)

PDF
Rich Internet Applications con JavaFX e NetBeans
PDF
SQL - RDBMS Concepts
PDF
D2W Stateful Controllers
PDF
Solr Troubleshooting - TreeMap approach
PPTX
Content Modeling Behavior
PPT
Sax Dom Tutorial
PPT
7 streams and error handling in java
PDF
Solr Black Belt Pre-conference
DOCX
บทที่5
PPT
JSP Standart Tag Lİbrary - JSTL
PDF
Objective-C Is Not Java
PDF
Using Apache Solr
PDF
ERRest - Designing a good REST service
PDF
code4lib 2011 preconference: What's New in Solr (since 1.4.1)
PPTX
04 darwino concepts and utility classes
PDF
Rapid Prototyping with Solr
PDF
Solr Recipes Workshop
PPTX
JSON in Solr: from top to bottom
Rich Internet Applications con JavaFX e NetBeans
SQL - RDBMS Concepts
D2W Stateful Controllers
Solr Troubleshooting - TreeMap approach
Content Modeling Behavior
Sax Dom Tutorial
7 streams and error handling in java
Solr Black Belt Pre-conference
บทที่5
JSP Standart Tag Lİbrary - JSTL
Objective-C Is Not Java
Using Apache Solr
ERRest - Designing a good REST service
code4lib 2011 preconference: What's New in Solr (since 1.4.1)
04 darwino concepts and utility classes
Rapid Prototyping with Solr
Solr Recipes Workshop
JSON in Solr: from top to bottom
Ad

Viewers also liked (20)

PPT
File class.48
PDF
Final Animation Assessment Presentation: The Abstraction of Bohemian Rhapsody.
PPTX
IoT and META-engineering with Service Templates
DOC
Core java questions
PDF
IEEE DEST CEE 2013 - Paper 4 (1) (1)
PPTX
Interface and abstraction
PDF
Java topology abstraction service for ip-vp ns
PDF
Intro to JavaScript
PPT
AR+S The Role Of Abstraction In Human Computer Interaction
PPTX
Java stereams
PPT
Java lecture
PPT
06 abstract-classes
PPTX
Object Oriented Programing JAVA presentaion
PPT
Character stream classes .52
PPT
Inner classes ,annoumous and outer classes in java
PDF
Java Inner Classes
PPTX
Encapsulation anonymous class
PPT
Abstract class
PDF
Operators in java
File class.48
Final Animation Assessment Presentation: The Abstraction of Bohemian Rhapsody.
IoT and META-engineering with Service Templates
Core java questions
IEEE DEST CEE 2013 - Paper 4 (1) (1)
Interface and abstraction
Java topology abstraction service for ip-vp ns
Intro to JavaScript
AR+S The Role Of Abstraction In Human Computer Interaction
Java stereams
Java lecture
06 abstract-classes
Object Oriented Programing JAVA presentaion
Character stream classes .52
Inner classes ,annoumous and outer classes in java
Java Inner Classes
Encapsulation anonymous class
Abstract class
Operators in java
Ad

Similar to Java JDBC (20)

PPT
Jdbc
PPTX
Jdbc ppt
PPT
JDBC Connecticity.ppt
PDF
Introduction to JDBC and database access in web applications
PPT
Jdbc oracle
PPTX
Jdbc Java Programming
PDF
Jdbc[1]
PDF
JDBC programming
PPTX
PDF
22jdbc
PDF
JDBC in Servlets
PPTX
Amr Mohamed Abd Elhamid_JAVA_JDBCData.pptx
PPTX
JDBC ppt
PDF
Java OOP Programming language (Part 8) - Java Database JDBC
PDF
Core Java Programming Language (JSE) : Chapter XIII - JDBC
PDF
Lecture17
PPTX
Lecture 1. java database connectivity
PPT
JDBC.ppt
PPSX
JDBC Part - 2
Jdbc
Jdbc ppt
JDBC Connecticity.ppt
Introduction to JDBC and database access in web applications
Jdbc oracle
Jdbc Java Programming
Jdbc[1]
JDBC programming
22jdbc
JDBC in Servlets
Amr Mohamed Abd Elhamid_JAVA_JDBCData.pptx
JDBC ppt
Java OOP Programming language (Part 8) - Java Database JDBC
Core Java Programming Language (JSE) : Chapter XIII - JDBC
Lecture17
Lecture 1. java database connectivity
JDBC.ppt
JDBC Part - 2

More from Jussi Pohjolainen (20)

PDF
Moved to Speakerdeck
PDF
Java Web Services
PDF
Box2D and libGDX
PDF
libGDX: Screens, Fonts and Preferences
PDF
libGDX: Tiled Maps
PDF
libGDX: User Input and Frame by Frame Animation
PDF
Intro to Building Android Games using libGDX
PDF
Advanced JavaScript Development
PDF
Introduction to JavaScript
PDF
Introduction to AngularJS
PDF
libGDX: Scene2D
PDF
libGDX: Simple Frame Animation
PDF
libGDX: Simple Frame Animation
PDF
libGDX: User Input
PDF
Implementing a Simple Game using libGDX
PDF
Building Android games using LibGDX
PDF
Android Threading
PDF
Creating Asha Games: Game Pausing, Orientation, Sensors and Gestures
PDF
Creating Games for Asha - platform
PDF
Intro to Asha UI
Moved to Speakerdeck
Java Web Services
Box2D and libGDX
libGDX: Screens, Fonts and Preferences
libGDX: Tiled Maps
libGDX: User Input and Frame by Frame Animation
Intro to Building Android Games using libGDX
Advanced JavaScript Development
Introduction to JavaScript
Introduction to AngularJS
libGDX: Scene2D
libGDX: Simple Frame Animation
libGDX: Simple Frame Animation
libGDX: User Input
Implementing a Simple Game using libGDX
Building Android games using LibGDX
Android Threading
Creating Asha Games: Game Pausing, Orientation, Sensors and Gestures
Creating Games for Asha - platform
Intro to Asha UI

Recently uploaded (20)

PDF
Heart disease approach using modified random forest and particle swarm optimi...
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Video forgery: An extensive analysis of inter-and intra-frame manipulation al...
PDF
gpt5_lecture_notes_comprehensive_20250812015547.pdf
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
NewMind AI Weekly Chronicles - August'25-Week II
PPTX
OMC Textile Division Presentation 2021.pptx
PDF
Network Security Unit 5.pdf for BCA BBA.
PPT
Teaching material agriculture food technology
PPTX
Programs and apps: productivity, graphics, security and other tools
PPTX
SOPHOS-XG Firewall Administrator PPT.pptx
PDF
Univ-Connecticut-ChatGPT-Presentaion.pdf
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
August Patch Tuesday
PDF
A comparative analysis of optical character recognition models for extracting...
PPTX
TechTalks-8-2019-Service-Management-ITIL-Refresh-ITIL-4-Framework-Supports-Ou...
Heart disease approach using modified random forest and particle swarm optimi...
Mobile App Security Testing_ A Comprehensive Guide.pdf
Spectral efficient network and resource selection model in 5G networks
Diabetes mellitus diagnosis method based random forest with bat algorithm
Video forgery: An extensive analysis of inter-and intra-frame manipulation al...
gpt5_lecture_notes_comprehensive_20250812015547.pdf
Advanced methodologies resolving dimensionality complications for autism neur...
NewMind AI Weekly Chronicles - August'25-Week II
OMC Textile Division Presentation 2021.pptx
Network Security Unit 5.pdf for BCA BBA.
Teaching material agriculture food technology
Programs and apps: productivity, graphics, security and other tools
SOPHOS-XG Firewall Administrator PPT.pptx
Univ-Connecticut-ChatGPT-Presentaion.pdf
Digital-Transformation-Roadmap-for-Companies.pptx
Encapsulation_ Review paper, used for researhc scholars
Unlocking AI with Model Context Protocol (MCP)
August Patch Tuesday
A comparative analysis of optical character recognition models for extracting...
TechTalks-8-2019-Service-Management-ITIL-Refresh-ITIL-4-Framework-Supports-Ou...

Java JDBC

  • 1. JDBC   Jussi  Pohjolainen   Tampere  University  of  Applied  Sciences  
  • 2. JDBC  Intro   •  Java  Database  Connec@vity  in  Java  since  1.1   •  API  in  Java  for  accessing  Databases   •  PlaDorm  independent,  Database  independent  
  • 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. 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. To  use  JDBC   1.  Register  driver   2.  Access  database   3.  Do  some  SQL  magic   4.  Handle  result   5.  Close  the  connec@on  
  • 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. 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. 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. 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. 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. 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. ResultSet   rs.next();   rs.next();   rs.next();   //  Prints  “Williams”   System.out.println(rs.getString(“Last  Name”));  
  • 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. Transac@ons   •  If  you  want  to  commit  several  sql  –  commands   into  one:   –  conn.setAutoCommit(false); –  // do some sql –  conn.commit(); –  conn.rollback();
  • 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. Scrollable  Resultset   Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); ResultSet srs = stmt.executeQuery(SQLQuery);
  • 17. Values   •  TYPE_FORWARD_ONLY  (default)   •  TYPE_SCROLL_INSENSITIVE   •  TYPE_SCROLL_SENSITIVE  –  all  updates   happens  immediately   •  CONCUR_READONLY   •  CONCUR_UPDATABLE  
  • 18. Methods  for  Scrollable  ResultSet   •  next()   •  previous()   •  beforeFirst()   •  aierLast()   •  absolute(int  x)  
  • 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. Update   while(rs.next()){ System.out.println(rs.getString("Firstname")); } rs.previous(); rs.updateString("Firstname", args[0]); rs.updateRow();
  • 21. Adding  a  Row   rs.moveToInsertRow(); rs.updateString("firstname", "Jack"); rs.updateString("lastname", "Smith"); rs.updateInt("idnumber", 20); rs.insertRow();
  • 22. Dele@ng  a  Row   •  rs.last(); •  rs.deleteRow();