SlideShare una empresa de Scribd logo
1 de 31
Descargar para leer sin conexión
Java DataBase
Connectivity (JDBC)
J2EE application model
J2EE is a multitiered distributed application model
  client machines
  the J2EE server machine
  the database or legacy machines at the back end
JDBC API
  JDBC is an interface which allows Java code to
  execute SQL statements inside relational
  databases
  Java       JDBC
                              driver
program
          connectivity      for Oracle
          data processing
           utilities           driver
                            for MySQL


              jdbc-odbc      ODBC
                bridge       driver
The JDBC-ODBC Bridge

 ODBC (Open Database Connectivity) is a
 Microsoft standard from the mid 1990’s.

 It is an API that allows C/C++ programs to
 execute SQL inside databases

 ODBC is supported by many products.
The JDBC-ODBC Bridge (Contd.)

 The JDBC-ODBC bridge allows Java code
 to use the C/C++ interface of ODBC
   it means that JDBC can access many different
   database products


 The layers of translation (Java --> C -->
 SQL) can slow down execution.
The JDBC-ODBC Bridge (Contd.)

 The JDBC-ODBC bridge comes free with
 the J2SE:
   called sun.jdbc.odbc.JdbcOdbcDriver



 The ODBC driver for Microsoft Access
 comes with MS Office
   so it is easy to connect Java and Access
JDBC Pseudo Code
All JDBC programs do the following:

Step 1) load the JDBC driver

Step 2) Specify the name and location of the database being used

Step 3) Connect to the database with a Connection object

Step 4) Execute a SQL query using a Statement object

Step 5) Get the results in a ResultSet object

Step 6) Finish by closing the ResultSet, Statement and Connection objects
JDBC API in J2SE
 Set up a database server (Oracle , MySQL, pointbase)
 Get a JDBC driver
     set CLASSPATH for driver lib
          Set classpath in windows, control panel->system->advanced->environment variable
          Set classpath in Solaris, set CLASSPATH to driver jar file
 Import the library
     import java.sql.*;
 Specify the URL to database server
     String url = "jdbc:pointbase://127.0.0.1/test“
 Load the JDBC driver
     Class.forName("com.pointbase.jdbc.jdbcUniversalDriver");
 Connect to database server
     Connection con = DriverManager.getConnection(url, “dbUser", “dbPass");
 Create SQL Statement
     stmt = con.createStatement();
 Execute SQL
     stmt.executeUpdate("insert into COFFEES " + "values('Colombian', 00101, 7.99, 0,
     0)");
     ResultSet rs = stmt.executeQuery(query);
JDBC Example
import java.sql.*;

public class SqlTest
{
      public static void main(String[] args)
      {
            try
            {

            // Step 1: Make a connection

            // Load the driver
            Class.forName("com.pointbase.jdbc.jdbcUniversalDriver");

            // Get a connection using this driver
            String url = "jdbc:pointbase://localhost/cs595";
            String dbUser = "PBPUBLIC";
            String dbPassword = "PBPUBLIC";

            Connection con = DriverManager.getConnection(url, dbUser, dbPassword);
JDBC Example (Contd.)
        Statement stmt = con.createStatement();
        String sql= "select * from Traps";

        ResultSet rs = stmt.executeQuery(sql);

        String name;
        double val;
        java.sql.Date date;

        while (rs.next())
        {
                            name = rs.getString("TrapName");
                            val = rs.getDouble("TrapValue");
                            date = rs.getDate("TrapDate");
                            System.out.println("name = " + name + " Value = " + val + " Date = " + date);
        }



        stmt.close();
        con.close();

        }
        catch(ClassNotFoundException ex1)
        {
                        System.out.println(ex1);
        }
        catch(SQLException ex2)
        {
                        System.out.println(ex2);
        }
    }
}
JDBC Diagram


                creates                creates               creates
DriverManager             Connection             Statement             ResultSet


                                                 SQL                        data

                          make link                          Driver
                          to driver
                                                   SQL                   data
Load Driver

DriverManager is responsible for establishing the
connection to the database through the driver.
e.g.
  Class.forName(
        "sun.jdbc.odbc.JdbcOdbcDriver");
  Connection conn =
        DriverManager.getConnection(url);
Specify the URL to database server
 The name and location of the database is
 given as a URL
   the details of the URL vary depending on the
   type of database that is being used
Database URL

 jdbc:pointbase: //host.domain.com: 9092 /data/file



 The comms      The machine Database The path to
                            port
 protocol       holding the          the database
                database.            on the machine



  e.g. jdbc:pointbase://localhost/myDB
Statement Object

 The Statement object provides a
 workspace where SQL queries can be
 created, executed, and results collected.
 e.g.
   Statement st =
              conn.createStatement():
   ResultSet rs = st.executeQuery(
         “ select * from Authors” );
         :
   st.close();
ResultSet Object

 Stores the results of a SQL query.

 A ResultSet object is similar to a ‘table’
 of answers, which can be examined by
 moving a ‘pointer’ (cursor).
Accessing a ResultSet


Cursor operations:
  first(), last(), next(), previous(), etc.
                         cursor
Typical code:                     23     John
  while( rs.next() ) {            5      Mark
    // process the row;           17     Paul
  }
                                  98     Peter
Accessing a ResultSet (Contd.)


 The ResultSet class contains many
 methods for accessing the value of a
 column of the current row
   can use the column name or position
   e.g. get the value in the lastName column:
    rs.getString("lastName")
    or rs.getString(2)
Accessing a ResultSet (Contd.)

   The ‘tricky’ aspect is that the values are
   SQL data, and so must be converted to
   Java types/objects.

   There are many methods for
   accessing/converting the data, e.g.
     getString(), getDate(), getInt(),
     getFloat(), getObject()
Meta Data

  Meta data is the information about the
  database:
    e.g. the number of columns, the types of
    the columns
    meta data is the schema information

                                         meta data
    ID      Name       Course    Mark
   007   James Bond   Shooting    99
   008   Aj. Andrew   Kung Fu     1
Accessing Meta Data

 The getMetaData() method can be used
 on a ResultSet object to create its meta
 data object.
 e.g.
   ResultSetMetaData md =
                   rs.getMetaData();
Using Meta Data

 int numCols = md.getColumnCount();

 for (int i = 0; i <= numCols; i++) {
   if (md.getColumnType(i) ==
                         Types.CHAR)
     System.out.println(
              md.getColumnName(i) )
 }
Database Connection Pooling

  Connection pooling is a technique
                                                  RDBMS
that was pioneered by database
vendors to allow multiple clients to
share a cached set of connection
objects that provide access to a
database resource
                                                  Connection
  Connection pools minimize the                      Pool
opening and closing of connections


                                                   Servlet



                                       Client 1      ……        Client n
JDBC in J2EE
Step 1: Start Sun Application Server PE 8

Step 2: Start PointBase

Step 3: Use J2EE admin to create connection pool

Step 4: Use J2EE admin to create JDBC data source

Step 5: import java.sql.*;

Step 6: get Context

Step 7: look up data source with JNDI

Step 8: Execute SQL and process result
Start Application Server & PointBase
Create Connection Pool Using Admin GUI
Create Data Source Using Admin GUI
Example: JDBC Using JNDI & Connection Pools


import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
import javax.sql.*;
import javax.naming.*;
import java.io.*;
import java.util.*;

public class SqlServlet extends HttpServlet
{
   public void doGet(HttpServletRequest req, HttpServletResponse res) throws
   ServletException
   {
          res.setContentType("text/plain");
Example: JDBC Using JNDI & Connection Pools (Contd.)

      try
      {

      PrintWriter pw = res.getWriter();

      String dbName = "java:comp/env/jdbc/TrapDB";

      InitialContext ic = new InitialContext();
      DataSource ds = (DataSource) ic.lookup(dbName);
      Connection con = ds.getConnection();

      Statement stmt = con.createStatement();
      String sql= "select * from Traps";

      ResultSet rs = stmt.executeQuery(sql);

      String name;
      double val;
      java.sql.Date date;

      while (rs.next())
      {
                    name = rs.getString("TrapName");
                    val = rs.getDouble("TrapValue");
                    date = rs.getDate("TrapDate");
                    pw.println("name = " + name + " Value = " + val + " Date = " + date);
      }
Example: JDBC Using JNDI & Connection Pools (Contd.)


        stmt.close();

        }
        catch(SQLException ex2)
        {
                System.out.println(ex2);
        }
        catch(IOException ex3)
        {
                System.out.println(ex3);
        }
        catch(Exception ex4)
        {
                System.out.println(ex4);
        }
    }
}
Reference
  Database and Enterprise Web Application Development in J2EE,
Xiachuan Yi, Computer Science Department, University of Georgia.

Más contenido relacionado

La actualidad más candente

Session06 handling xml data
Session06  handling xml dataSession06  handling xml data
Session06 handling xml datakendyhuu
 
Map-Reduce and Apache Hadoop
Map-Reduce and Apache HadoopMap-Reduce and Apache Hadoop
Map-Reduce and Apache HadoopSvetlin Nakov
 
Jdbc oracle
Jdbc oracleJdbc oracle
Jdbc oracleyazidds2
 
Building node.js applications with Database Jones
Building node.js applications with Database JonesBuilding node.js applications with Database Jones
Building node.js applications with Database JonesJohn David Duncan
 
Validating JSON -- Percona Live 2021 presentation
Validating JSON -- Percona Live 2021 presentationValidating JSON -- Percona Live 2021 presentation
Validating JSON -- Percona Live 2021 presentationDave Stokes
 
The Ring programming language version 1.8 book - Part 33 of 202
The Ring programming language version 1.8 book - Part 33 of 202The Ring programming language version 1.8 book - Part 33 of 202
The Ring programming language version 1.8 book - Part 33 of 202Mahmoud Samir Fayed
 
#36.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_재직자환급교육,실업자교육,국비지원교육, 자바교육,구...
#36.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_재직자환급교육,실업자교육,국비지원교육, 자바교육,구...#36.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_재직자환급교육,실업자교육,국비지원교육, 자바교육,구...
#36.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_재직자환급교육,실업자교육,국비지원교육, 자바교육,구...탑크리에듀(구로디지털단지역3번출구 2분거리)
 
Spring data presentation
Spring data presentationSpring data presentation
Spring data presentationOleksii Usyk
 
An introduction into Spring Data
An introduction into Spring DataAn introduction into Spring Data
An introduction into Spring DataOliver Gierke
 
Advanced java practical semester 6_computer science
Advanced java practical semester 6_computer scienceAdvanced java practical semester 6_computer science
Advanced java practical semester 6_computer scienceNiraj Bharambe
 
The Ring programming language version 1.5.3 book - Part 28 of 184
The Ring programming language version 1.5.3 book - Part 28 of 184The Ring programming language version 1.5.3 book - Part 28 of 184
The Ring programming language version 1.5.3 book - Part 28 of 184Mahmoud Samir Fayed
 
The Ring programming language version 1.2 book - Part 17 of 84
The Ring programming language version 1.2 book - Part 17 of 84The Ring programming language version 1.2 book - Part 17 of 84
The Ring programming language version 1.2 book - Part 17 of 84Mahmoud Samir Fayed
 
The Ring programming language version 1.7 book - Part 31 of 196
The Ring programming language version 1.7 book - Part 31 of 196The Ring programming language version 1.7 book - Part 31 of 196
The Ring programming language version 1.7 book - Part 31 of 196Mahmoud Samir Fayed
 
2001: JNDI Its all in the Context
2001:  JNDI Its all in the Context2001:  JNDI Its all in the Context
2001: JNDI Its all in the ContextRussell Castagnaro
 
Cloudera Impala, updated for v1.0
Cloudera Impala, updated for v1.0Cloudera Impala, updated for v1.0
Cloudera Impala, updated for v1.0Scott Leberknight
 

La actualidad más candente (20)

Session06 handling xml data
Session06  handling xml dataSession06  handling xml data
Session06 handling xml data
 
Map-Reduce and Apache Hadoop
Map-Reduce and Apache HadoopMap-Reduce and Apache Hadoop
Map-Reduce and Apache Hadoop
 
Jdbc oracle
Jdbc oracleJdbc oracle
Jdbc oracle
 
Building node.js applications with Database Jones
Building node.js applications with Database JonesBuilding node.js applications with Database Jones
Building node.js applications with Database Jones
 
My sql tutorial-oscon-2012
My sql tutorial-oscon-2012My sql tutorial-oscon-2012
My sql tutorial-oscon-2012
 
Java &amp; banco de dados
Java &amp; banco de dadosJava &amp; banco de dados
Java &amp; banco de dados
 
Validating JSON -- Percona Live 2021 presentation
Validating JSON -- Percona Live 2021 presentationValidating JSON -- Percona Live 2021 presentation
Validating JSON -- Percona Live 2021 presentation
 
The Ring programming language version 1.8 book - Part 33 of 202
The Ring programming language version 1.8 book - Part 33 of 202The Ring programming language version 1.8 book - Part 33 of 202
The Ring programming language version 1.8 book - Part 33 of 202
 
#36.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_재직자환급교육,실업자교육,국비지원교육, 자바교육,구...
#36.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_재직자환급교육,실업자교육,국비지원교육, 자바교육,구...#36.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_재직자환급교육,실업자교육,국비지원교육, 자바교육,구...
#36.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_재직자환급교육,실업자교육,국비지원교육, 자바교육,구...
 
22jdbc
22jdbc22jdbc
22jdbc
 
Spring data presentation
Spring data presentationSpring data presentation
Spring data presentation
 
An introduction into Spring Data
An introduction into Spring DataAn introduction into Spring Data
An introduction into Spring Data
 
Jdbc
JdbcJdbc
Jdbc
 
Advanced java practical semester 6_computer science
Advanced java practical semester 6_computer scienceAdvanced java practical semester 6_computer science
Advanced java practical semester 6_computer science
 
The Ring programming language version 1.5.3 book - Part 28 of 184
The Ring programming language version 1.5.3 book - Part 28 of 184The Ring programming language version 1.5.3 book - Part 28 of 184
The Ring programming language version 1.5.3 book - Part 28 of 184
 
The Ring programming language version 1.2 book - Part 17 of 84
The Ring programming language version 1.2 book - Part 17 of 84The Ring programming language version 1.2 book - Part 17 of 84
The Ring programming language version 1.2 book - Part 17 of 84
 
The Ring programming language version 1.7 book - Part 31 of 196
The Ring programming language version 1.7 book - Part 31 of 196The Ring programming language version 1.7 book - Part 31 of 196
The Ring programming language version 1.7 book - Part 31 of 196
 
2001: JNDI Its all in the Context
2001:  JNDI Its all in the Context2001:  JNDI Its all in the Context
2001: JNDI Its all in the Context
 
Cloudera Impala, updated for v1.0
Cloudera Impala, updated for v1.0Cloudera Impala, updated for v1.0
Cloudera Impala, updated for v1.0
 
Jndi
JndiJndi
Jndi
 

Destacado (20)

Servlets intro
Servlets introServlets intro
Servlets intro
 
Servlet sessions
Servlet sessionsServlet sessions
Servlet sessions
 
01 session tracking
01   session tracking01   session tracking
01 session tracking
 
Servlet Filter
Servlet FilterServlet Filter
Servlet Filter
 
Jsp
JspJsp
Jsp
 
Jsp
JspJsp
Jsp
 
Jsp (java server page)
Jsp (java server page)Jsp (java server page)
Jsp (java server page)
 
Jsp Introduction Tutorial
Jsp Introduction TutorialJsp Introduction Tutorial
Jsp Introduction Tutorial
 
JSP
JSPJSP
JSP
 
Jsp chapter 1
Jsp chapter 1Jsp chapter 1
Jsp chapter 1
 
Lecture 3: Servlets - Session Management
Lecture 3:  Servlets - Session ManagementLecture 3:  Servlets - Session Management
Lecture 3: Servlets - Session Management
 
Java Server Pages
Java Server PagesJava Server Pages
Java Server Pages
 
Jsp presentation
Jsp presentationJsp presentation
Jsp presentation
 
Jsp ppt
Jsp pptJsp ppt
Jsp ppt
 
Java servlet life cycle - methods ppt
Java servlet life cycle - methods pptJava servlet life cycle - methods ppt
Java servlet life cycle - methods ppt
 
Engaging Educators and Evangelists
Engaging Educators and EvangelistsEngaging Educators and Evangelists
Engaging Educators and Evangelists
 
Tarea cuenta dropbox
Tarea cuenta dropboxTarea cuenta dropbox
Tarea cuenta dropbox
 
Kostiakova
KostiakovaKostiakova
Kostiakova
 
Pressure ppt s kyle
Pressure ppt s kylePressure ppt s kyle
Pressure ppt s kyle
 
Papagalite ot martin-chakarov
Papagalite ot martin-chakarovPapagalite ot martin-chakarov
Papagalite ot martin-chakarov
 

Similar a Lecture17 (20)

JDBC
JDBCJDBC
JDBC
 
Jdbc
JdbcJdbc
Jdbc
 
Jdbc
JdbcJdbc
Jdbc
 
Jdbc (database in java)
Jdbc (database in java)Jdbc (database in java)
Jdbc (database in java)
 
Jdbc 1
Jdbc 1Jdbc 1
Jdbc 1
 
Jdbc sasidhar
Jdbc  sasidharJdbc  sasidhar
Jdbc sasidhar
 
jdbc_presentation.ppt
jdbc_presentation.pptjdbc_presentation.ppt
jdbc_presentation.ppt
 
Introduction to JDBC and database access in web applications
Introduction to JDBC and database access in web applicationsIntroduction to JDBC and database access in web applications
Introduction to JDBC and database access in web applications
 
Jdbc[1]
Jdbc[1]Jdbc[1]
Jdbc[1]
 
JDBC programming
JDBC programmingJDBC programming
JDBC programming
 
Jdbc ppt
Jdbc pptJdbc ppt
Jdbc ppt
 
JDBC for CSQL Database
JDBC for CSQL DatabaseJDBC for CSQL Database
JDBC for CSQL Database
 
JDBC (2).ppt
JDBC (2).pptJDBC (2).ppt
JDBC (2).ppt
 
JDBC Tutorial
JDBC TutorialJDBC Tutorial
JDBC Tutorial
 
Data Access with JDBC
Data Access with JDBCData Access with JDBC
Data Access with JDBC
 
Lecture 1. java database connectivity
Lecture 1. java database connectivityLecture 1. java database connectivity
Lecture 1. java database connectivity
 
JDBC Connecticity.ppt
JDBC Connecticity.pptJDBC Connecticity.ppt
JDBC Connecticity.ppt
 
Jdbc ja
Jdbc jaJdbc ja
Jdbc ja
 
Jdbc api
Jdbc apiJdbc api
Jdbc api
 
Executing Sql Commands
Executing Sql CommandsExecuting Sql Commands
Executing Sql Commands
 

Más de vantinhkhuc (20)

Url programming
Url programmingUrl programming
Url programming
 
Security overview
Security overviewSecurity overview
Security overview
 
Rmi
RmiRmi
Rmi
 
Md5
Md5Md5
Md5
 
Lecture11 b
Lecture11 bLecture11 b
Lecture11 b
 
Lecture10
Lecture10Lecture10
Lecture10
 
Lecture9
Lecture9Lecture9
Lecture9
 
Lecture6
Lecture6Lecture6
Lecture6
 
Jsse
JsseJsse
Jsse
 
Jsf intro
Jsf introJsf intro
Jsf intro
 
Jsp examples
Jsp examplesJsp examples
Jsp examples
 
Jpa
JpaJpa
Jpa
 
Ejb examples
Ejb examplesEjb examples
Ejb examples
 
Corba
CorbaCorba
Corba
 
Ajax
AjaxAjax
Ajax
 
Ejb intro
Ejb introEjb intro
Ejb intro
 
Chc6b0c6a1ng 12
Chc6b0c6a1ng 12Chc6b0c6a1ng 12
Chc6b0c6a1ng 12
 
Ch06
Ch06Ch06
Ch06
 
Bai4
Bai4Bai4
Bai4
 
Ajas11 alok
Ajas11 alokAjas11 alok
Ajas11 alok
 

Lecture17

  • 2. J2EE application model J2EE is a multitiered distributed application model client machines the J2EE server machine the database or legacy machines at the back end
  • 3. JDBC API JDBC is an interface which allows Java code to execute SQL statements inside relational databases Java JDBC driver program connectivity for Oracle data processing utilities driver for MySQL jdbc-odbc ODBC bridge driver
  • 4. The JDBC-ODBC Bridge ODBC (Open Database Connectivity) is a Microsoft standard from the mid 1990’s. It is an API that allows C/C++ programs to execute SQL inside databases ODBC is supported by many products.
  • 5. The JDBC-ODBC Bridge (Contd.) The JDBC-ODBC bridge allows Java code to use the C/C++ interface of ODBC it means that JDBC can access many different database products The layers of translation (Java --> C --> SQL) can slow down execution.
  • 6. The JDBC-ODBC Bridge (Contd.) The JDBC-ODBC bridge comes free with the J2SE: called sun.jdbc.odbc.JdbcOdbcDriver The ODBC driver for Microsoft Access comes with MS Office so it is easy to connect Java and Access
  • 7. JDBC Pseudo Code All JDBC programs do the following: Step 1) load the JDBC driver Step 2) Specify the name and location of the database being used Step 3) Connect to the database with a Connection object Step 4) Execute a SQL query using a Statement object Step 5) Get the results in a ResultSet object Step 6) Finish by closing the ResultSet, Statement and Connection objects
  • 8. JDBC API in J2SE Set up a database server (Oracle , MySQL, pointbase) Get a JDBC driver set CLASSPATH for driver lib Set classpath in windows, control panel->system->advanced->environment variable Set classpath in Solaris, set CLASSPATH to driver jar file Import the library import java.sql.*; Specify the URL to database server String url = "jdbc:pointbase://127.0.0.1/test“ Load the JDBC driver Class.forName("com.pointbase.jdbc.jdbcUniversalDriver"); Connect to database server Connection con = DriverManager.getConnection(url, “dbUser", “dbPass"); Create SQL Statement stmt = con.createStatement(); Execute SQL stmt.executeUpdate("insert into COFFEES " + "values('Colombian', 00101, 7.99, 0, 0)"); ResultSet rs = stmt.executeQuery(query);
  • 9. JDBC Example import java.sql.*; public class SqlTest { public static void main(String[] args) { try { // Step 1: Make a connection // Load the driver Class.forName("com.pointbase.jdbc.jdbcUniversalDriver"); // Get a connection using this driver String url = "jdbc:pointbase://localhost/cs595"; String dbUser = "PBPUBLIC"; String dbPassword = "PBPUBLIC"; Connection con = DriverManager.getConnection(url, dbUser, dbPassword);
  • 10. JDBC Example (Contd.) Statement stmt = con.createStatement(); String sql= "select * from Traps"; ResultSet rs = stmt.executeQuery(sql); String name; double val; java.sql.Date date; while (rs.next()) { name = rs.getString("TrapName"); val = rs.getDouble("TrapValue"); date = rs.getDate("TrapDate"); System.out.println("name = " + name + " Value = " + val + " Date = " + date); } stmt.close(); con.close(); } catch(ClassNotFoundException ex1) { System.out.println(ex1); } catch(SQLException ex2) { System.out.println(ex2); } } }
  • 11. JDBC Diagram creates creates creates DriverManager Connection Statement ResultSet SQL data make link Driver to driver SQL data
  • 12. Load Driver DriverManager is responsible for establishing the connection to the database through the driver. e.g. Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver"); Connection conn = DriverManager.getConnection(url);
  • 13. Specify the URL to database server The name and location of the database is given as a URL the details of the URL vary depending on the type of database that is being used
  • 14. Database URL jdbc:pointbase: //host.domain.com: 9092 /data/file The comms The machine Database The path to port protocol holding the the database database. on the machine e.g. jdbc:pointbase://localhost/myDB
  • 15. Statement Object The Statement object provides a workspace where SQL queries can be created, executed, and results collected. e.g. Statement st = conn.createStatement(): ResultSet rs = st.executeQuery( “ select * from Authors” ); : st.close();
  • 16. ResultSet Object Stores the results of a SQL query. A ResultSet object is similar to a ‘table’ of answers, which can be examined by moving a ‘pointer’ (cursor).
  • 17. Accessing a ResultSet Cursor operations: first(), last(), next(), previous(), etc. cursor Typical code: 23 John while( rs.next() ) { 5 Mark // process the row; 17 Paul } 98 Peter
  • 18. Accessing a ResultSet (Contd.) The ResultSet class contains many methods for accessing the value of a column of the current row can use the column name or position e.g. get the value in the lastName column: rs.getString("lastName") or rs.getString(2)
  • 19. Accessing a ResultSet (Contd.) The ‘tricky’ aspect is that the values are SQL data, and so must be converted to Java types/objects. There are many methods for accessing/converting the data, e.g. getString(), getDate(), getInt(), getFloat(), getObject()
  • 20. Meta Data Meta data is the information about the database: e.g. the number of columns, the types of the columns meta data is the schema information meta data ID Name Course Mark 007 James Bond Shooting 99 008 Aj. Andrew Kung Fu 1
  • 21. Accessing Meta Data The getMetaData() method can be used on a ResultSet object to create its meta data object. e.g. ResultSetMetaData md = rs.getMetaData();
  • 22. Using Meta Data int numCols = md.getColumnCount(); for (int i = 0; i <= numCols; i++) { if (md.getColumnType(i) == Types.CHAR) System.out.println( md.getColumnName(i) ) }
  • 23. Database Connection Pooling Connection pooling is a technique RDBMS that was pioneered by database vendors to allow multiple clients to share a cached set of connection objects that provide access to a database resource Connection Connection pools minimize the Pool opening and closing of connections Servlet Client 1 …… Client n
  • 24. JDBC in J2EE Step 1: Start Sun Application Server PE 8 Step 2: Start PointBase Step 3: Use J2EE admin to create connection pool Step 4: Use J2EE admin to create JDBC data source Step 5: import java.sql.*; Step 6: get Context Step 7: look up data source with JNDI Step 8: Execute SQL and process result
  • 26. Create Connection Pool Using Admin GUI
  • 27. Create Data Source Using Admin GUI
  • 28. Example: JDBC Using JNDI & Connection Pools import javax.servlet.*; import javax.servlet.http.*; import java.sql.*; import javax.sql.*; import javax.naming.*; import java.io.*; import java.util.*; public class SqlServlet extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException { res.setContentType("text/plain");
  • 29. Example: JDBC Using JNDI & Connection Pools (Contd.) try { PrintWriter pw = res.getWriter(); String dbName = "java:comp/env/jdbc/TrapDB"; InitialContext ic = new InitialContext(); DataSource ds = (DataSource) ic.lookup(dbName); Connection con = ds.getConnection(); Statement stmt = con.createStatement(); String sql= "select * from Traps"; ResultSet rs = stmt.executeQuery(sql); String name; double val; java.sql.Date date; while (rs.next()) { name = rs.getString("TrapName"); val = rs.getDouble("TrapValue"); date = rs.getDate("TrapDate"); pw.println("name = " + name + " Value = " + val + " Date = " + date); }
  • 30. Example: JDBC Using JNDI & Connection Pools (Contd.) stmt.close(); } catch(SQLException ex2) { System.out.println(ex2); } catch(IOException ex3) { System.out.println(ex3); } catch(Exception ex4) { System.out.println(ex4); } } }
  • 31. Reference Database and Enterprise Web Application Development in J2EE, Xiachuan Yi, Computer Science Department, University of Georgia.