JDBC

INTRODUCTION TO JDBC

What is JDBC?

JDBC stands for Java Database Connectivity, which is a standard Java API for database-independent connectivity between the Java programming language and a wide range of databases.

JDBC ARCHITECTURE

The JDBC API supports both two-tier and three-tier processing models for database access but in general JDBC Architecture consists of two layers:

JDBC API: This provides the application-to-JDBC Manager connection.

JDBC Driver API: This supports the JDBC Manager-to-Driver Connection.

ARCHITECTURE OF JDBC .

COMPONENTS OF JDBC  JDBC API  Provides various methods and interfaces for communication with databases  JDBC DriverManager  Loads database-specific drivers  JDBC Test Suite  Used to test operation being performed by JDBC drivers  JDBC-ODBC Bridge  Connects database drivers to database. .

JDBC DRIVER TYPES .

 Type 1 Driver(JDBC-ODBC Bridge Driver) DBMS Call JDBC Call JDBC API Java APP JDBCODBC Bridge Driver ODBC API ODBC Driver .

JDBC-ODBC bridge acts as an interface between client and database server. . In this type.  The driver converts JDBC method calls into ODBC function calls. The bridge is usually used when there is no pure-Java driver available for a particular database.

. The driver is platform-dependent as it makes use of ODBC which in turn depends on native libraries of the operating system. using this driver has got other dependencies such as ODBC must be installed on client machine.  Also.

.  Represents vendor independent driver.ADVANTAGE OF TYPE-1 DRIVER  Allows you to communicate with all the databases supported by ODBC driver.

this might not be suitable for applets.  The ODBC driver needs to be installed on the client machine  considering the client-side software needed.DISADVANTAGE OF TYPE-1 DRIVER  Performance overhead since the calls have to go through the JDBC overhead bridge to the ODBC driver. .

 Type 2 Driver(JAVA To Native API) Native Call JDBC Call JDBC API DBMS Specific Native API Type-2 Driver Java APP .

is a database driver implementation that uses the client-side libraries or native libraries of the database. The JDBC type 2 driver.  The driver converts JDBC method calls into native calls which is written in C.C++ .

ADVANTAGE OF TYPE – 2 DRIVER  Better performance than Type 1 since no jdbc to odbc translation is needed .

 Cannot be used in internet due the client side software needed  Not all databases give the client side library .DISADVANTAGE OF TYPE – 2 DRIVER  The vendor client library needs to be installed on the client machine.

TYPE – 3 DRIVER(JAVA TO NETWORK PROTOCOL) Server Specific JDBC Call DBMS Call Middleware Server JDBC API  Java APP Type-3 Driver Server Driver .

 Type-3 Driver translates JDBC calls into database server independent and middleware server specific calls.  The middleware server can be added in an application with some additional functionality. . performance improvement and connection availability.  With the help of middleware server the translated JDBC calls are further translated into database specific calls. such as pool management.

ADVANTAGE OF TYPE – 3 DRIVER  Since the communication between client and the middleware server is database independent. and so on). query results.  The Middleware Server (Can be a full fledged J2EE Application server) can provide typical middleware services like caching (connections. load balancing etc . there is no need for the vendor db library on the client machine.

of n/w calls  It is costlier  .  An extra layer added may result in a timebottleneck  It performs tasks slowly due to increased no.DISADVANTAGE Requires database-specific coding to be done in the middle tier.

TYPE.4 DRIVER(JAVA TO DATABASE DRIVER) DB Specific Call JDBC Call JDBC API DBMS Specific Network Protocol Type-4 Driver  Java APP .

 This type of driver does not require any native library  Type-4 Driver translates JDBC calls into database specific n/w calls.  It is installed inside the Java Virtual Machine of the client. . Type-4 Driver is pure java driver. which implements the database protocol to interact directly with database.

Serves as pure java driver and auto downloadable   Does not require native library Does not require middleware server .ADVANTAGE OF TYPE-4 DRIVER   Web application mainly used this driver.

.DISADVANTAGE  There is a separate driver needed for each database at the client side.

sql package.  Depending on the requirements these classes and interfaces can be used. .JDBC API  If any java application or an applet wants to connect with a database then there are various classes and interfaces available in java.

 The java.sql package contains following classes. Date  DriverManager  DriverPropertyInfo  SQLPermission  Time  TimeStamp (represents both time and date including nanoseconds )  Types  .

name of cols and datatype of cols)  DatabaseMetaData(display the type of driver we are using)  .sql package contains following interfaces: Driver  Connection  Statement  PreparedStatement  CallableStatement  ResultSet  Blob  Clob  ResultSetMetaData(display no.of cols. The java.

DriverManager Description Create a connection with specific database The task of DriverManager is to manage the database driver It executes SQL statements for particular connection and retrieve the results It allows the programmer to create prepared SQL statements It executes stored procedures This interface provides methods to get result row by row generated by SELECT statements Java.Connection Java.Statement Java.sql.sql.ResultSet .Class or Interface Java.CallableStatement Java.sql.sql.sql.sql.PreparedStatement Java.

)   Connection and statement Pooling(connection pooling means that connections are reused rather than created each time a connection is requested. is maintained by a connection pooling. a memory cache of database connections.)   Distributed transaction Rowsets .sql package contains following classes and interfaces DataSource (general-purpose mechanism for connecting to a database and making SQL based queries and updates. The javax. To facilitate connection reuse. called a connection pool.

STATEMENT INTERFACE  There are three types of statement interfaces :Simple Statement Prepared Statement Callable Statement Returns void void Signature addBatch(String sql) clearBatch() int[] int[] int[] executeBatch() executeUpdate() executeQuery() .

Statement stmt = con.odbc.  Create a statement  .*.jdbc.forName(“sun.createStatement().sql.  Load the driver   Establish connection to the database  Connection con = Driver. Class.STEP FOR USING JDBC  Import java.getConnection(“jdbc:odbc:database”).sql package  import java.JdbcOdbcDriver”).

executeQuery(“select * from database”).next()) con.close().  Close the connection and statement  .  Retrieve the results  while(res. Execute the statement  ResultSet res = stmt.

.  It’s a very simple and easy so it is also called as “Simple Statement”.  The statement interface has several methods for execute the SQL statements and also get the appropriate result as per the query sent to the database.SIMPLE STATEMENT  The Statement interface is used to execute a static query.

sql.mysql. import java. String url = "jdbc:mysql://localhost:3306/test". String userName = "root".sql.EXAMPLE JAVA DATABASE CONNECTIVITY    import java.Driver".SQLException. public class DBConnection {      String driverName = "com. String query = “select * from student” . String password = "admin".sql.Connection. import java. .DriverManager.jdbc.

out. Connection conn = DriverManager.getInt(“col2”)+”\t”).println(rs. password). userName.next()){ System.println(rs. System.getConnection(url.createStatement(). System.out.getString(“col1”)+”\t”).out.executeUpdate(query).getInt(“col3”)). while(rs.out. } }           .forName(driverName).println(“col1\tcol2\tcol3”).     public Connection getConnection() { try { Class. ResultSet rs = stmt. Statement stmt = con. System.println(rs.

 } catch (SQLException e) {  e.  }  public static void main(String[] args) {  DBConnection dbc = new DBConnection().  }  return conn.printStackTrace().  } }  .  dbc.getConnection().printStackTrace().catch (ClassNotFoundException e) {  e.

 . which can be executed multiple times. is subclass of the Statement interface.  The PreparedStatement interface.PREPARED STATEMENT Use when you plan to use the SQL statements many times. can be used to represent precompiled query.  The PreparedStatement interface accepts input parameters at runtime.

A parameter that provides both input and output values. You retrieve values from theOUT parameters with the getXXX() methods. You bind variables with the setXXX() methods and retrieve values with the getXXX() methods. You bind values to IN parameters with the setXXX() methods. OUT INOUT .Parameter Description IN A parameter whose value is unknown when the SQL statement is created. A parameter whose value is supplied by the SQL statement it returns.

String query=“insert into stu values(?. ps.?)”.?. ps.”abbc”).’’tiger”).”scott”.*.prepareStatement(query).OracleDriver”). .12. ps.jdbc.forName(“oracle.38).setString(1.sql. PreparedStatement ps = con.getConnection(“jdbc:oracle:thin:local host”.setDouble(3.setInt(2.driver.import java. Connection con = DriverManager.34). public class PreparedStatement{ Class.

int i = ps.executeUpdate(); System.out.println(“record inserted successfully:”+i); ps.setString(1,”abbc2”); ps.setInt(2,39); ps.setDouble(3,14.34); i=ps.executeUpdate(); System.out.println(“record inserted once again”+i); con.Close();

} }

CALLABLE STATEMENT

A java.sql.CallableStatement interface object is used to call stored

procedures from the database. It is the standard way to execute
stored procedure for all DBMS/RDBMS. A stored procedure is an object stored in a database.

A procedure with IN and OUT parameter can be executed only in
this Callable Statement

An OUT parameter in the stored procedure is represented by the ?

An OUT parameter is registered using registerOUTParameter()
method

After the CallableSatement() is executed, the OUT parameter are to be obtained using the getXXX() method

For eg :

registerOUTParamet(int index,Type type)

where

index – is the relative position of OUT parameter in SQL statement

type – is the SQL data type of OUT parameter

LONGVARCH AR). .executeQuery(). CallableStatement csmt = con.registerOutParameter(3.   ResultSet rs= csmt.?.Types.setString(1.”Ruchi”).  csmt.5000).prepareCall(Execute emp(?.setInt(2. csmt.  csmt.?)).

out_m1 OUT number. Declaration Section temp_m2 number. temp_m1 NUMBER. out_sname OUT varchar2. out_m2 OUT number ) is temp_sregno number. temp_sname VARCHAR2(10). SQL statement for stored procedure CREATE OR REPLACE PROCEDURE proc1( in_sregno NUMBER. .

temp_m2 FROM mark WHERE sregno = in_sregno.m1. out_sname : = temp_m1.temp_m1. . BEGIN SELECT sregno. temp_sname. Execution Section  END.m2 INTO temp_sregno.sname. out_sname : = temp_m1. out_sname : = temp_sname.

String url = “jdbc:odbc:stu”.JdbcOdbcDriver”). . CallableStatement csmt = con. public class Callb{ public static void main(String[] args) { int in_sregno.forName(“sun. Connection con = null.”scott”.odbc.prepareCall(“{call proc1(?. try{ Class.?) }”).?. int ret_code.jdbc. in_sregno=1111.”tiger”). conn = DriverManager.?.getConnection(url.

csmt. int o_m2 = csmt.getInt(3). Types. csmt.getInt(4).csmt.getString(2).INTEGER).executeUpdate(). String o_sname = csmt. int o_m1 = csmt. csmt.setInt(1. Types.INTEGER).registerOutParameter(4. csmt. Types.registerOutParameter(3.in_sregno). .VARCHAR).registerOutParameter(2.

out.getErrorCode().println(“sregno”+”\t”+”name”+”mark1”+\t+”mark2”).      System. } } } .println(in_sregno+”\t”+o_sname+”\t”+o_m1+”\t”+o_ m2).out.close(). con.out.close().getMessage()).println(ret_code+e. } catch(SQLException e)  { ret_code = e. System.close(). con. System. csmt.

RESULTSET INTERFACE  The executeQuery() and getResultSet() when called on Statement.  The ResultSet objects contain results after the execution of SQL statements. PreparedStatement and CallableStatement returns objects of type ResultSet.  The next() method moves cursor to the next row of result set .

jdbc.EXAMPLE USING RESULTSET import java. String sql.JdbcOdbcDrive r”). public class res{ public static void main(String[] args) { Statement stmt.forName(“sun. try{ Class.sql*.odbc. . ResultSet reset.

getConnection(“jdbc:odbc:stu_base” ).close(). stmt=con. while(reset.out.println(“Name\n”). reset=stmt. stmt. con. } .close().createStatement().next()) System.executeQuery(sql).Connection con = DriverManager.println(reset. System.out.getString(“name”)). sql=“select name from stu”.

out.println(“Sql error”).out.catch(SQLException e) { System.println(“Sql error”). } catch(ClassNotFoundException c) { System. } } } .

BATCHUPDATE Batch Processing allows you to group related SQL statements into a batch and submit them with one call to the database.  . you reduce the amount of communication overhead.  Allows you to submit DDL and DML operations to process the data simultaneously. thereby improving performance.  When you send several SQL statements to the database at once.

you can remove them with theclearBatch() method. However. and each element of the array represents the update count for the respective update statement. and CallableStatement is used to add individual statements to the batch.  .  The executeBatch() returns an array of integers. The executeBatch() is used to start the execution of all the statements grouped together. PreparedStatement.The addBatch() method of Statement. This method removes all the statements you added with the addBatch() method. you cannot selectively choose which statement to remove.  Just as you can add statements to a batch for processing.

 Execute all the SQL statements using executeBatch() method on created statement object.  Add as many as SQL statements you like into batch using addBatch() method on created statement object.  Finally.  .  Set auto-commit to false using setAutoCommit().BATCHING WITH STATEMENT OBJECT: Create a Statement object using either createStatement() methods. commit all the changes using commit() method.

age) VALUES(200.createStatement(). 'Ali'.'Zia'. last. // Create statement object Statement stmt = conn.  // Set auto-commit to false conn. 30)".setAutoCommit(false). .  // Create SQL statement String SQL = "INSERT INTO Employees (id. first.

addBatch(SQL). 'Kumar'. . last. age) " + "VALUES(201. first.  // Create one more SQL statement String SQL = "INSERT INTO Employees (id. stmt.'Raj'. 35)". // Add above SQL statement in the batch.

executeBatch().  stmt. . String SQL = "UPDATE Employees SET age = 35 " + "WHERE id = 100".commit().addBatch(SQL).addBatch(SQL). stmt. conn. count = stmt.

*. import java. .*.BLOB EXAMPLE  This example will insert data having blob datatype import java.*.sql. import java. public class InsertBlob{ public static void main(String[] args)throws Exception{ Connection con = null.io.util.

executeUpdate().Integer.fis. FIleInputStream fis = new FileInputStream(f).driver. File f = new File(“myimage.Class.getConnection(“jdbc:oracle:thin:local host”.gif”).forName(“oracle. ps.jdbc.length()).”scott”.setBinaryStream(2.’’tiger”). con = DriverManager.OracleDriver”).setInt(1.photo)values(?.prepareStatement(“insert into emp(emp_no. PreparedStatement ps = con.?)”).parseInt(101)). } } . ps. int i=ps. con.(int)f.close().

util.io.CLOB EXAMPLE  This example will insert data having blob datatype import java.sql.*. import java. public class InsertClob{ public static void main(String[] args)throws Exception{ Connection con = null. .*.*. import java.

int i=ps.(int)f.forName(“oracle.driver.parseInt(101)). FileReader fr = new FileReader(f).description)values(?.?)”). ps.fr. PreparedStatement ps =con.setInt(1. ps.’’tiger”).prepareStatement(“insert into empProfile (emp_no.jdbc.length()).Integer.getConnection(“jdbc:oracle:thin:local host”.OracleDriver”).setCharacterStream(2. File f = new File().Class.executeUpdate() } } .”scott”. con = DriverManager.