JDBC
JDBC
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:
ARCHITECTURE OF JDBC
COMPONENTS OF JDBC
JDBC API
JDBC DriverManager
JDBC-ODBC Bridge
JDBC Call
JDBC API
Java APP
ODBC
API
ODBC Driver
In this type, JDBC-ODBC bridge acts as an interface between client and database server.
The driver is platform-dependent as it makes use of ODBC which in turn depends on native libraries of
Also, using this driver has got other dependencies such as ODBC must be installed on client machine.
Allows you to communicate with all the databases supported by ODBC driver.
Performance overhead since the calls have to go through the JDBC overhead bridge to the ODBC driver.
considering the client-side software needed, this might not be suitable for applets.
JDBC Call
JDBC API
Java APP
The driver converts JDBC method calls into native calls which is written in C,C++
Middleware Server
JDBC API
Java APP
Type-3 Driver translates JDBC calls into database server independent and middleware server specific calls.
Since the communication between client and the middleware server is database independent, there is no need for the vendor db library on the client machine.
The Middleware Server (Can be a full fledged J2EE Application server) can provide typical
DISADVANTAGE
Requires database-specific coding to be done in the middle tier. An extra layer added may result in a timebottleneck It performs tasks slowly due to increased no. of n/w calls It is costlier
JDBC API
Java APP
Web application mainly used this driver. Serves as pure java driver and auto downloadable
DISADVANTAGE
There is a separate driver needed for each database at the client side.
JDBC API
The
Date DriverManager DriverPropertyInfo SQLPermission Time TimeStamp (represents both time and date including nanoseconds ) Types
The
Driver Connection Statement PreparedStatement CallableStatement ResultSet Blob Clob ResultSetMetaData(display no.of cols,name of cols and datatype of cols) DatabaseMetaData(display the type of driver we are using)
Class or Interface
Java.sql.Connection Java.sql.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.sql.Statement
Java.sql.PreparedStatement Java.sql.CallableStatement
Java.sql.ResultSet
The
Connection and statement Pooling(connection pooling means that connections are reused rather than created each time a connection is requested. To facilitate connection reuse, a memory cache of database connections, called a connection pool, is maintained by a connection pooling.)
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()
Create a statement
while(res.next())
con.close();
SIMPLE STATEMENT
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.
String driverName = "com.mysql.jdbc.Driver"; String url = "jdbc:mysql://localhost:3306/test"; String userName = "root"; String password = "admin";
String query = select * from student ;
public Connection getConnection() { try { Class.forName(driverName); Connection conn = DriverManager.getConnection(url, userName, password); Statement stmt = con.createStatement(); ResultSet rs = stmt.executeUpdate(query); System.out.println(col1\tcol2\tcol3); while(rs.next()){ System.out.println(rs.getString(col1)+\t); System.out.println(rs.getInt(col2)+\t); System.out.println(rs.getInt(col3)); } }
} public static void main(String[] args) { DBConnection dbc = new DBConnection(); dbc.getConnection(); } }
PREPARED STATEMENT
Use when you plan to use the SQL statements many times. The PreparedStatement interface accepts input parameters at runtime. The PreparedStatement interface, is subclass of the Statement interface, can be used to represent precompiled query, which can be executed multiple times.
Parameter
Description
IN
A parameter whose value is unknown when the SQL statement is created. You bind values to IN parameters with the setXXX() methods. A parameter whose value is supplied by the SQL statement it returns. You retrieve values from theOUT parameters with the getXXX() methods. A parameter that provides both input and output values. You bind variables with the setXXX() methods and retrieve values with the getXXX() methods.
OUT
INOUT
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
After the CallableSatement() is executed, the OUT parameter are to be obtained using the getXXX() method
For eg :
where
in_sregno NUMBER,
out_sname OUT varchar2, out_m1 OUT number, out_m2 OUT number ) is temp_sregno number; temp_sname VARCHAR2(10); temp_m1 NUMBER;
Declaration Section
temp_m2 number;
BEGIN
SELECT sregno,sname,m1,m2
INTO temp_sregno, temp_sname,temp_m1,temp_m2 FROM mark WHERE sregno = in_sregno;
out_sname : = temp_sname;
out_sname : = temp_m1; out_sname : = temp_m1; Execution Section
END;
public class Callb{ public static void main(String[] args) { int in_sregno; int ret_code; Connection con = null; try{ Class.forName(sun.jdbc.odbc.JdbcOdbcDriver); String url = jdbc:odbc:stu; conn = DriverManager.getConnection(url,scott,tiger); in_sregno=1111; CallableStatement csmt = con.prepareCall({call proc1(?,?,?,?) });
csmt.setInt(1,in_sregno); csmt.registerOutParameter(2, Types.VARCHAR); csmt.registerOutParameter(3, Types.INTEGER); csmt.registerOutParameter(4, Types.INTEGER); csmt.executeUpdate(); String o_sname = csmt.getString(2); int o_m1 = csmt.getInt(3); int o_m2 = csmt.getInt(4);
RESULTSET INTERFACE
The executeQuery() and getResultSet() when called on Statement, PreparedStatement and CallableStatement returns objects of type ResultSet.
The ResultSet objects contain results after the execution of SQL statements.
Connection con = DriverManager.getConnection(jdbc:odbc:stu_base ); stmt=con.createStatement(); sql=select name from stu; reset=stmt.executeQuery(sql); System.out.println(Name\n); while(reset.next()) System.out.println(reset.getString(name)); stmt.close(); con.close(); }
BATCHUPDATE
Batch Processing allows you to group related SQL statements into a batch and submit them with one call to the database. When you send several SQL statements to the database at once, you reduce the amount of communication overhead, thereby improving performance. Allows you to submit DDL and DML operations to process the data simultaneously.
The addBatch() method of Statement, PreparedStatement, and CallableStatement is used to add individual statements to the batch. The executeBatch() is used to start the execution of all the statements grouped together. The executeBatch() returns an array of integers, and each element of the array represents the update count for the respective update statement. Just as you can add statements to a batch for processing, you can remove them with theclearBatch() method. This method removes all the statements you added with the addBatch() method. However, you cannot selectively choose which statement to remove.
// Create SQL statement String SQL = "INSERT INTO Employees (id, first, last, age) VALUES(200,'Zia', 'Ali', 30)";
stmt.addBatch(SQL); String SQL = "UPDATE Employees SET age = 35 " + "WHERE id = 100";
BLOB EXAMPLE
import java.sql.*; import java.util.*; import java.io.*; public class InsertBlob{ public static void main(String[] args)throws Exception{
Connection con = null;
Class.forName(oracle.jdbc.driver.OracleDriver); con = DriverManager.getConnection(jdbc:oracle:thin:local host,scott,tiger); PreparedStatement ps = con.prepareStatement(insert into emp(emp_no,photo)values(?,?)); ps.setInt(1,Integer.parseInt(101)); File f = new File(myimage.gif); FIleInputStream fis = new FileInputStream(f); ps.setBinaryStream(2,fis,(int)f.length()); int i=ps.executeUpdate(); con.close(); } }
CLOB EXAMPLE
Class.forName(oracle.jdbc.driver.OracleDriver);
con = DriverManager.getConnection(jdbc:oracle:thin:local host,scott,tiger); PreparedStatement ps =con.prepareStatement(insert into empProfile (emp_no,description)values(?,?)); ps.setInt(1,Integer.parseInt(101)); File f = new File(); FileReader fr = new FileReader(f); ps.setCharacterStream(2,fr,(int)f.length()); int i=ps.executeUpdate()
} }