You are on page 1of 44

JDBC

Why JDBC ?
Using JDBC , java program can interact with RDBMS like Oracle , SQL Server ,DB2 ,Access etc Java program becomes RDBMS independent , that is same java program can interact with any kind of RDBMS

What do I need to use JDBC?


The java.sql.* package, which comes with the JDK (1.1.x and above). A JDBC compliant driver (either provided directly from the database vendor, or a third-party vendor)

Java program

JDBC API (provided by Sun)

JDBC Driver(from RDBMS vendor)

RDBMS

JDBC Driver Types


There are different ways to implement a JDBC driver that accesses a database:
Type 1 Type 2 Type 3 Type 4 JDBC-ODBC Bridge Drivers Native-API Partly Java Drivers Net-protocol All Java Drivers Native Protocol All-Java Drivers

Type 1 Driver Client Computer


JDBC-ODBC bridge Driver RDBMS

Java program

JDBC API (provided by Sun)

ODBC driver

Type 1 Driver Client Computer


JDBC-ODBC bridge Driver RDBMS

Java program

JDBC API (provided by Sun)

ODBC driver

ODBC driver for Oracle

JDBC-ODBC Bridge
RDBMS

ODBC Driver JDBC-ODBC Driver

Client

Java Program

JDBC-ODBC Bridge
Translates JDBC calls to ODBC calls Requires installed ODBC Driver (non-Java) on client machine Comes with JDK

JDBC-ODBC Bridge
Advantages: Can be useful for databases where other methods not available (e.g., MSAccess) Disadvantages: Client computer needs to be configured with ODBC driver and ODBC instance which specifies database server and other information JDBC performance relies on ODBC driver

Type 2 Driver Client Computer


Type 2 JDBCDriver RDBMS

Java program

JDBC API

RDBMS Client

(provided by Sun)

Type 4 Driver Client Computer


Type 4 JDBC- Driver RDBMS

Java program

JDBC API (provided by Sun)

Java to Native-API (ORACLE)


RDBMS
SQL Net Listener

SQL Net Client

JDBC Driver

Client

Java Program

Native-API Partly Java Drivers


Driver contains Java code that makes JNI (Java Native Interface) calls to vendor C/C++ Driver code Driver converts JDBC calls into client API calls of the DBMS like Oracle, Sybase, Informix, DB2 or etc

Native-API Partly Java Drivers


Advantages: Performs better than ODBC bridge Most database vendors provide this driver as part of client software Disadvantages: Cant use it in un-trusted applets Client code must be loaded on each client computer Native libraries need to be installed and configured on client computer

Java to Network Protocol (Oracle)


RDBMS
SQL Net Listener

Middle tier (DBAnywhere)

JDBC Driver

Client
Java Program

Net-protocol All Java Drivers


Translates JDBC API calls into a DBMS-independent net protocol which is then translated to a DBMS protocol by a server Able to connect all of its Java technology-based clients to many different databases Very flexible Scalable No code on client and multiple databases may be accessed A middleware is present to implement RDBMS vendor protocol

Net-protocol All Java Drivers


Advantages: Used in three-tier solution deployed over internet Database product is protected behind a middle tier Middle tier software can interface to any database product Client requires smaller size of driver than other types Disadvantages: Costly due to middle layer

Java to Native Database Protocol


(Oracle)
SQL Net Listener

RDBMS

JDBC Driver

Client
Java Program

Native Protocol All-Java Drivers


Driver converts JDBC technology calls into the network protocol used by DBMS engine directly Allows a direct call from the client machine to the DBMS server and is a practical solution for Intranet access Database vendors are providers of this type driver Whole driver is implemented using DBMS engine protocol

Native Protocol All-Java Drivers


Advantages: Driver can be deployed over internet Driver directly talks to database therefore, better performance Web deployed applets Disadvantages: Cannot use many vendor database engines

Simple JDBC Program


Load JDBC Driver implementation Obtain connection to driver/database Execute query Process query results Release resources

How to Connect?
Connection involves two steps: Step 1 - Loading the driver Step 2 - Making the connection

Example Program Step 1 - Load the Driver


import java.sql.*; try { Class.forName(oracle.jdbc.driver.OracleDriver); } catch(ClassNotFoundException) {
// Couldnt find JDBC driver to load !

Step 1 - Load the Driver


import java.sql.*; // REMEMBER TO IMPORT JDBC Package public class JdbcTest{ public static void main(String args[]){ try{ Class.forName(oracle.jdbc.driver.OracleDriver); //rest of the codes }catch(ClassNotFoundExeption e){ }catch(Exception e){ } }// end of main }// end of class

Points to be noted
There exists a class whose name in : Class in java.lang package forName is static method of the class :Class. Parameter of forName is string . This string is package qualified class name.
In jdbc we have to supply appropriate driver class name

this method throws a checked exception

Points to be noted
Task of forName is to load byte codes of the specified class name in JVM memory. If it fails to do that , it will throw : ClassNotFoundException

Points to be noted
JDBC Driver is available as jar file .
Jdbc driver is java program.

Driver class is part of this jar file . This jar file must be configured in classpath.
otherwise forName will fail to load this class and it will throw ClassNotFound Exception.

Example Program Step 2 - Obtain a Connection


Connection con = DriverManager.getConnection( jdbc:oracle:thin:@machinename:1521:instancename, user, password ); public static Connection getConnection(String url,String user,String password) throws SQLException

What Driver creates the Connection ?


URL specifies the driver (subprotocol) and the data source/database system Ex. jdbc:odbc:MyDataSource Ex. jdbc:oracle:thin:@machine:1521:insname Subprotocol specifies a particular kind of database connectivity that may be supported by more than one driver

JDBC URLs
Specially formatted string , which contains informations like :
What type of driver to use .(type 1, type 2 ,.) What rdbms to connect. What is hostname,port Other databs information

Always starts with jdbc:


jdbc:subprotocol:subname

Subprotocol :
Determines what rdbms driver to use i.e driver for oracle / driver for DB2 /driver for mysql

Subname :
What type to use ( Type 1 , Type 2 ,.) Format depends on subprotocol.

Examples jdbc:odbc:datasource;dataoptions jdbc:oracle:thin:@orderserver:1521:petStore

jdbc:oracle:oci8:@database
jdbc:db2://orderserver:50000/SAMPLE jdbc:mysql://orderserver:3306/orderdb

Executing a SQL
In JDBC SQL statements can be of two types
Not precompiled (Basic SQL) Precompiled (by the driver)

To execute a not precompiled SQL , an instance of java.sql.Statement is required. java.sql.Statement is an interface Statement stmt = con.createStatement();
Where con is an instance of java.sql.Connection

SQL Statements
Create some form of Statement
Statement
Represents a basic SQL statement Statement stmt = conn.createStatement();

PreparedStatement
A precompiled SQL statement, which can offer improved performance, especially for large/complex SQL statements

Callable Statement
Allows JDBC programs access to stored procedures

Class.forName(oracle.jdbc.driver.OracleDriver); String url=jdbc:oracle:thin:@machine:1521:ins-name; Connection conn=DriverManager.getConnection(url,scott,tiger); Statement stmt=conn.createStatement();

How to execute Not precompiled SQL ?


Execute query methods on statement object that you have created :
public ResultSet executeQuery(String sql) throws SQLException
To execute basic SQL Set of records returned as ResultSet object

public int executeUpdate(String sql) throws SQLException


To execute ISERT,UPDATE,DELETE Returns updatecount

public boolean execute(String sql) throws SQLException


To execute SELECT OR DML Returns : true , if ResultSet Returns : false , if updatecount

Class.forName(oracle.jdbc.driver.OracleDriver); String url=jdbc:oracle:thin:@machine:1521:ins-name; Connection conn=DriverManager.getConnection(url,scott,tiger); Statement stmt=conn.createStatement(); ResultSet rs=stmt.executeQuery(select empno,ename from emp);

Working with ResultSet


A table of data representing the set of records returned from SELECT statement A ResultSet object maintains a cursor pointing to its current row of data . Initially the cursor is positioned before the first row. ResultSet object has a method , next() , which moves the cursor to the next record.
public boolean next() throws SQLException

It returns false if there is no more record in the ResultSet object.

Working with ResultSet


Call getter methods (getInt(),getFloat()) to retrieve values from current row.
Column index or name must be passed as a parameter to getter methods Passing column index is more efficient. Column index starts from 1 .

When getter is invoked , JDBC driver converts underlying data of the RDBMS into java language type JDBC specification has defined mapping from SQL type to java type

Class.forName(oracle.jdbc.driver.OracleDriver); String url=jdbc:oracle:thin:@machine:1521:ins-name; Connection conn=DriverManager.getConnection(url,scott,tiger); Statement stmt=conn.createStatement(); ResultSet rs=stmt.executeQuery(select empno,ename from emp); while ( rs.next()){ int eno=rs.getInt(1); String name=rs.getString(ename) ; // sysout }

Precompiled SQL statement


An object of java.sql.PreparedStatement represents a precompiled SQL statement. A SQL statement is precompiled and stored in a PreparedStatement object. This is useful if same SQL statement executed many times

Creating prepared statement


Invoke prepareStatement method of Connection object
Pass the SQL that will be executed many times as a argument . PreparedStatement pstmt = con.prepareStatement("UPDATE EMPLOYEES SET SALARY = ? WHERE ID = ?"); Symbol ? represents place holders , where values will fitted at time of execution. Every place holder are identified by therie position , which starts with 1 and increments left to right Use setter methods to set value at execution time.

Example
PreparedStatement pstmt = con.prepareStatement("UPDATE EMPLOYEES SET SALARY = ? WHERE ID = ?"); pstmt.setFloat(1, 15383.00f); pstmt.setInt(2, 7992) ; int updatecount=pstmt.executeUpdate(); pstmt.close()

Executing Stored Procedure


An object of java.sql.CallableStatement is used to execute a stored procedure . Stored proc SQL escape syntax to be used to call stored proc in standard way. prepareCall method of the Connection object to be called , to get a CallableStatement object.
CallableStatemet cstmt=con.prepareCall( ?=

You might also like