Sunteți pe pagina 1din 61

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

In this type, JDBC-ODBC bridge acts as an interface between client and database server.

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.

Also, using this driver has got other dependencies such as ODBC must be installed on client machine.

ADVANTAGE OF TYPE-1 DRIVER

Allows you to communicate with all the databases supported by ODBC driver.

Represents vendor independent driver.

DISADVANTAGE OF TYPE-1 DRIVER

Performance overhead since the calls have to go through the JDBC overhead bridge to the ODBC driver.

The ODBC driver needs to be installed on the client machine

considering the client-side software needed, this might not be suitable for applets.

Type 2 Driver(JAVA To Native API)


Native Call

JDBC Call

JDBC API

DBMS Specific Native API Type-2 Driver

Java APP

The JDBC type 2 driver, is a database driver


implementation that uses the client-side libraries or native libraries of the database.

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

DISADVANTAGE OF TYPE 2 DRIVER

The vendor client library needs to be installed on


the client machine.

Cannot be used in internet due the client side software needed

Not all databases give the client side library

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.

With the help of middleware server the translated JDBC calls


are further translated into database specific calls.

The middleware server can be added in an application with

some additional functionality, such as pool management,


performance improvement and connection availability.

ADVANTAGE OF TYPE 3 DRIVER

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

middleware services like caching (connections,


query results, and so on), load balancing etc

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

TYPE- 4 DRIVER(JAVA TO DATABASE DRIVER)


DB Specific Call JDBC Call

JDBC API

DBMS Specific Network Protocol Type-4 Driver

Java APP

Type-4 Driver is pure java driver, which implements

the database protocol to interact directly with


database.

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.

ADVANTAGE OF TYPE-4 DRIVER


Web application mainly used this driver. Serves as pure java driver and auto downloadable

Does not require native library


Does not require middleware server

DISADVANTAGE

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

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.sql package.

Depending on the requirements these classes and interfaces can be used.

The

java.sql package contains following classes.

Date DriverManager DriverPropertyInfo SQLPermission Time TimeStamp (represents both time and date including nanoseconds ) Types

The

java.sql package contains following interfaces:

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

javax.sql package contains following classes and interfaces


DataSource (general-purpose mechanism for connecting to a database and making SQL based queries and updates.)

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.)

Distributed transaction Rowsets

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

STEP FOR USING JDBC

Import java.sql package

import java.sql.*; Class.forName(sun.jdbc.odbc.JdbcOdbcDriver);

Load the driver

Establish connection to the database

Connection con = Driver.getConnection(jdbc:odbc:database);


Statement stmt = con.createStatement();

Create a statement

Execute the statement

ResultSet res = stmt.executeQuery(select * from database);

Retrieve the results

while(res.next())
con.close();

Close the connection and statement

SIMPLE STATEMENT

The Statement interface is used to execute a static query.

Its 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.

EXAMPLE JAVA DATABASE CONNECTIVITY


import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class DBConnection {

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

catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } return conn;

} 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

import java.sql.*; public class PreparedStatement{


Class.forName(oracle.jdbc.driver.OracleDriver);

Connection con = DriverManager.getConnection(jdbc:oracle:thin:local host,scott,tiger); String query=insert into stu values(?,?,?);


PreparedStatement ps = con.prepareStatement(query); ps.setString(1,abbc); ps.setInt(2,38); ps.setDouble(3,12.34);

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

CallableStatement csmt = con.prepareCall(Execute emp(?,?,?));

csmt.setString(1,Ruchi); csmt.setInt(2,5000); csmt.registerOutParameter(3,Types.LONGVARCH AR);


ResultSet rs= csmt.executeQuery();

SQL statement for stored procedure CREATE OR REPLACE PROCEDURE proc1(

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

System.out.println(sregno+\t+name+mark1+\t+mark2); System.out.println(in_sregno+\t+o_sname+\t+o_m1+\t+o_ m2); csmt.close(); con.close(); } catch(SQLException e)

ret_code = e.getErrorCode(); System.out.println(ret_code+e.getMessage()); con.close();


} } }

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.

The next() method moves cursor to the next row of


result set

EXAMPLE USING RESULTSET


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

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

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

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.

BATCHING WITH STATEMENT OBJECT:


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

// Create statement object Statement stmt =


conn.createStatement();

// Set auto-commit to false conn.setAutoCommit(false);

// Create SQL statement String SQL = "INSERT INTO Employees (id, first, last, age) VALUES(200,'Zia', 'Ali', 30)";

// Add above SQL statement in the batch. stmt.addBatch(SQL);

// Create one more SQL statement String SQL =


"INSERT INTO Employees (id, first, last, age) " + "VALUES(201,'Raj', 'Kumar', 35)";

stmt.addBatch(SQL); String SQL = "UPDATE Employees SET age = 35 " + "WHERE id = 100";

stmt.addBatch(SQL); count = stmt.executeBatch(); conn.commit();

BLOB EXAMPLE

This example will insert data having blob datatype

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

This example will insert data having blob datatype

import java.sql.*; import java.util.*; import java.io.*;


public class InsertClob{ 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 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()

} }

S-ar putea să vă placă și