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

PPTX
JDBC ppt
PPT
JDBC Tutorial
PPTX
Jdbc in servlets
PPTX
1. java database connectivity (jdbc)
PPT
JDBC – Java Database Connectivity
PPT
Java database connectivity
PPTX
DataBase Connectivity
JDBC ppt
JDBC Tutorial
Jdbc in servlets
1. java database connectivity (jdbc)
JDBC – Java Database Connectivity
Java database connectivity
DataBase Connectivity

What's hot (20)

PPT
java jdbc connection
PDF
Overview Of JDBC
PPTX
Java Database Connectivity (JDBC)
PPT
Java Database Connectivity
PPTX
Database Access With JDBC
PPTX
KEY
JDBC Basics (In 20 Minutes Flat)
PPT
JDBC Java Database Connectivity
PPT
Java database connectivity with MYSQL
PPT
3 database-jdbc(1)
PPT
Jdbc ppt
PPT
Jdbc complete
PPSX
JDBC: java DataBase connectivity
PPT
PPTX
Lecture 1. java database connectivity
PPTX
Java database connectivity with MySql
PPS
Jdbc example program with access and MySql
PPT
Jdbc (database in java)
PPTX
PPS
Jdbc api
java jdbc connection
Overview Of JDBC
Java Database Connectivity (JDBC)
Java Database Connectivity
Database Access With JDBC
JDBC Basics (In 20 Minutes Flat)
JDBC Java Database Connectivity
Java database connectivity with MYSQL
3 database-jdbc(1)
Jdbc ppt
Jdbc complete
JDBC: java DataBase connectivity
Lecture 1. java database connectivity
Java database connectivity with MySql
Jdbc example program with access and MySql
Jdbc (database in java)
Jdbc api
Ad

Viewers also liked (16)

PPS
Jdbc architecture and driver types ppt
PPTX
Software Process Models
PPTX
PPTX
SDLC and Software Process Models
PPTX
Java Programming- Introduction to Java Applet Programs
PPT
Types of Software testing
PPT
PPTX
JDBC Driver Types
PPT
Jdbc in java
PPT
Java applets
PPSX
Seminar on java
PPT
Different type of_software_testing - copy
PPT
Testing concepts ppt
Jdbc architecture and driver types ppt
Software Process Models
SDLC and Software Process Models
Java Programming- Introduction to Java Applet Programs
Types of Software testing
JDBC Driver Types
Jdbc in java
Java applets
Seminar on java
Different type of_software_testing - copy
Testing concepts ppt
Ad

Similar to Jdbc (20)

PPTX
Jdbc presentation
PPT
Jdbc oracle
PDF
java4th.pdf bilgisayar mühendisliği bölümü
PDF
Java OOP Programming language (Part 8) - Java Database JDBC
PDF
Jdbc[1]
PDF
JDBC programming
PPTX
Jdbc Java Programming
PDF
Introduction to JDBC and JDBC Drivers
PPTX
Jdbc
PPT
jdbc_presentation.ppt
PPT
JDBC.ppt
PDF
PPT
PDF
Jdbc 1
PPTX
Jdbc ppt
PDF
java arlow jdbc tutorial(java programming tutorials)
PPT
Jdbc ppt
PPT
Jdbc sasidhar
PDF
Introduction to JDBC and database access in web applications
PPT
4. Database Connectivity using JDBC .ppt
Jdbc presentation
Jdbc oracle
java4th.pdf bilgisayar mühendisliği bölümü
Java OOP Programming language (Part 8) - Java Database JDBC
Jdbc[1]
JDBC programming
Jdbc Java Programming
Introduction to JDBC and JDBC Drivers
Jdbc
jdbc_presentation.ppt
JDBC.ppt
Jdbc 1
Jdbc ppt
java arlow jdbc tutorial(java programming tutorials)
Jdbc ppt
Jdbc sasidhar
Introduction to JDBC and database access in web applications
4. Database Connectivity using JDBC .ppt

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
Transforming Manufacturing operations through Intelligent Integrations
PDF
Modernizing your data center with Dell and AMD
PDF
Sensors and Actuators in IoT Systems using pdf
PDF
DevOps & Developer Experience Summer BBQ
PDF
CIFDAQ's Market Wrap: Ethereum Leads, Bitcoin Lags, Institutions Shift
PDF
BLW VOCATIONAL TRAINING SUMMER INTERNSHIP REPORT
PPTX
How to Build Crypto Derivative Exchanges from Scratch.pptx
PPTX
ABU RAUP TUGAS TIK kelas 8 hjhgjhgg.pptx
PDF
REPORT: Heating appliances market in Poland 2024
PDF
madgavkar20181017ppt McKinsey Presentation.pdf
PDF
NewMind AI Monthly Chronicles - July 2025
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
Reimagining Insurance: Connected Data for Confident Decisions.pdf
PDF
solutions_manual_-_materials___processing_in_manufacturing__demargo_.pdf
PDF
A Day in the Life of Location Data - Turning Where into How.pdf
PDF
How Onsite IT Support Drives Business Efficiency, Security, and Growth.pdf
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PPTX
Telecom Fraud Prevention Guide | Hyperlink InfoSystem
PDF
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
PPTX
Web Security: Login Bypass, SQLi, CSRF & XSS.pptx
Transforming Manufacturing operations through Intelligent Integrations
Modernizing your data center with Dell and AMD
Sensors and Actuators in IoT Systems using pdf
DevOps & Developer Experience Summer BBQ
CIFDAQ's Market Wrap: Ethereum Leads, Bitcoin Lags, Institutions Shift
BLW VOCATIONAL TRAINING SUMMER INTERNSHIP REPORT
How to Build Crypto Derivative Exchanges from Scratch.pptx
ABU RAUP TUGAS TIK kelas 8 hjhgjhgg.pptx
REPORT: Heating appliances market in Poland 2024
madgavkar20181017ppt McKinsey Presentation.pdf
NewMind AI Monthly Chronicles - July 2025
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Reimagining Insurance: Connected Data for Confident Decisions.pdf
solutions_manual_-_materials___processing_in_manufacturing__demargo_.pdf
A Day in the Life of Location Data - Turning Where into How.pdf
How Onsite IT Support Drives Business Efficiency, Security, and Growth.pdf
Understanding_Digital_Forensics_Presentation.pptx
Telecom Fraud Prevention Guide | Hyperlink InfoSystem
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
Web Security: Login Bypass, SQLi, CSRF & XSS.pptx

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();