Unit8 JDBC
Unit8 JDBC
With the help of JDBC driver we can connect with different types of databases.
JDBC have so many classes and interfaces that allow a java application to send request made by
user to any specific DBMS(Data Base Management System).
Components of JDBC:
JDBC has four main components as under and with the help of these components java
application can connect with database.
The JDBC API - it provides various methods and interfaces for easy communication with
database.
The JDBC test suite - it will be used to test an operation being performed by JDBC drivers.
JDBC Specification:
JDBC 2.0 - it provides JDBC API(JDBC 2.0 Core API and JDBC 2.0 Optional Package API).
JDBC 3.0 - it provides classes and interfaces in two packages(java.sql and javax.sql).
Connection management
Enhanced support for large object like BLOB(Binary Large Object) and CLOB(Character Large
Object).
JavaSoft provides three JDBC product components as part of the Java Developer's Kit (JDK):
The JDBC driver manager is the backbone of the JDB architecture. It actually is quite small and
simple; its primary function is to connect Java applications to the correct JDBC driver and then
get out of the way
JDBC Architecture:
JDBC API provides classes and interfaces to handle request made by user and response made by
database.
DriverManager
Driver
Connection
Statement
PreparedStatement
CallableStatement
ResultSet
DatabaseMetaData
ResultSetMetaData
It uses some database specific drivers to communicate our J2EE application to database.
With the help of DriverManager class than we connect to a specific database with the help of
spcific database driver.
We will learn all that four drivers with architecture in next chapter.
Some drivers are pure java drivers and some are partial.
So with this kind of JDBC architecture we can communicate with specific database.
JDBC Drivers:
There are four categories of drivers by which developer can apply a connection between Client
(The JAVA application or an applet) to a DBMS.
(3) Type 3 Driver : Network-Protocol Driver (Pure Java driver for database Middleware).
(4) Type 4 Driver : Native-Protocol Driver (Pure Java driver directly connected to database).
The JDBC type 1 driver which is also known as a JDBC-ODBC Bridge is a convert JDBC
methods into ODBC function calls.
The driver is a platform dependent because it uses ODBC which is depends on native libraries of
the operating system and also the driver needs other installation for example, ODBC must be
installed on the computer and the database must support ODBC driver.
Type 1 is the simplest compare to all other driver but it’s a platform specific i.e. only on
Microsoft platform.
1. Start
The JDBC-ODBC Bridge is use only when there is no PURE-JAVA driver available for a
particular database.
The driver is a platform dependent because it uses ODBC which is depends on native libraries of
the operating system and also the driver needs other installation for example, ODBC must be
installed on the computer and the database must support ODBC driver.
Java DB is Oracle's supported distribution of the open source Apache Derby database. Its ease of
use, standards compliance, full feature set, and small footprint make it the ideal database for Java
developers. Java DB is written in the Java programming language, providing "write once, run
anywhere" portability. It can be embedded in Java applications, requiring zero administration by
the developer or user. It can also be used in client server mode. Java DB is fully transactional and
provides a standard SQL interface.
The JDBC driver manager is the backbone of the JDB architecture. It actually is quite small and
simple; its primary function is to connect Java applications to the correct JDBC driver and then
get out of the way
Architecture Diagram:
Advantage:
(1) Connect to almost any database on any system, for which ODBC driver is installed.
(2) It’s an easy for installation as well as easy(simplest) to use as compare the all other driver.
Disadvantage:
(1) The ODBC Driver needs to be installed on the client machine.
(2) It’s a not a purely platform independent because its use ODBC which is depends on native
libraries of the operating system on client machine.
(3) Not suitable for applets because the ODBC driver needs to be installed on the client machine.
The JDBC type 2 driver is uses the libraries of the database which is available at client side and
this driver converts the JDBC method calls into native calls of the database so this driver is also
known as a Native-API driver.
Architecture Diagram :
Advantage:
(1) There is no implantation of JDBC-ODBC Bridge so it’s faster than a type 1 driver; hence
the performance is better as compare the type 1 driver (JDBC-ODBC Bridge).
Disadvantage:
(1) On the client machine require the extra installation because this driver uses the vendor client
libraries.
(2) The Client side software needed so cannot use such type of driver in the web-based
application.
(3) Type 3 Driver: Network-Protocol Driver (Pure Java driver for database Middleware) :-
The JDBC type 3 driver uses the middle tier(application server) between the calling program and
the database and this middle tier converts JDBC method calls into the vendor specific database
protocol and the same driver can be used for multiple databases also so it’s also known as a
Network-Protocol driver as well as a JAVA driver for database middleware.
Architecture Diagram:
Advantage:
(1) There is no need for the vendor database library on the client machine because the
middleware is database independent and it communicates with client.
(2) Type 3 driver can be used in any web application as well as on internet also because there is
no any software require at client side.
(3) A single driver can handle any database at client side so there is no need a separate driver for
each database.
(4) The middleware server can also provide the typical services such as connections, auditing,
load balancing, logging etc.
Disadvantage:
(2) At the middleware develop the database specific coding, may be increase complexity.
The JDBC type 4 driver converts JDBC method calls directly into the vendor specific database
protocol and in between do not need to be converted any other formatted system so this is the
fastest way to communicate quires to DBMS and it is completely written in JAVA because of
that this is also known as the “direct to database Pure JAVA driver”.
If we are using type-4 driver in oracle then we need to add jar file to the class path because it was
given by third party.
Process:
Java Application → JDBC APIs → JDBC Driver Manager → Type 4 Driver (Pure JAVA
Driver) → Database Server
(2) No translation or middleware layers are used so consider as a faster than other drivers.
(3) The all process of the application-to-database connection can manage by JVM so the
debugging is also managed easily.
Disadvantage:
(1)There is a separate driver needed for each database at the client side.
(2) Drivers are Database dependent, as different database vendors use different network
protocols.
JDBC APIs:
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.
Some of them are list out the below which are used to perform the various tasks with database as
well as for connection.
The Connection interface used to connect java application with particular database.
After crating the connection with database we can execute SQL statements for that particular
connection using object of Connection and retrieve the results.
The interface has few methods that makes changes to the database temporary or permanently.
Method Description
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.
Method Description
This method frees an object of type Statement
void close()
from database and other JDBC resources.
The Prepared Statement interface is used to execute a dynamic query (parameterized SQL
statement) with IN parameter.
IN Parameter:-
Syntax :
Where XXX means a data type as per the value we want to pass in the query.
For example,
PreparedStatement ps = con.prepareStatement(query);
ps.setInt(1, 1);
The Prepared statement interface has several methods to execute the parameterized SQL
statements and retrieve appropriate result as per the query sent to the database.
Method Description
The JDBC API is based mainly on a set of interfaces, not classes. It's up to the manufacturer of
the driver to implement the interfaces with their own set of classes.
A class diagram that shows the basic JDBC classes and interfaces; these make up the core API.
Notice that the only concrete class is DriverManager. The rest of the core API is a set of
interfaces.
Statement and PreparedStatement objects are used to execute SQL statements. CallableStatement
objects are used to execute stored procedures.
A Connection can also be used to get a DatabaseMetaData object describing a database's
functionality.
A ResultSet can be used to get the actual returned data or a ResultSetMetaData object that can
be queried to identify the types of data returned in the ResultSet.
//obtain a statement
Statement st=con.createStatement();
//for oracle
String query="create table mytable1(col1 varchar2(20),col2 number,col3 number(10,2))";
//for MySQL
//String query="create table mytable1(col1 varchar(20),col2 numeric,col3
numeric(10,2))";
}
public static Connection prepareConnection() throws SQLException,ClassNotFoundException
{
// TODO Auto-generated method stub
//Oracle Database
String driverClassName="oracle.jdbc.driver.OracleDriver";
String url="jdbc:oracle:thin:@localhost:1521:xe";
String userName="system";
String password="manager";
return conn;
}
}
//2. InsertEx.java
//obtain a statement
Statement st=con.createStatement();
return conn;
}
}
//3. PreparedStatementEx1.java
package com.yellaswamy.jdbcexamples;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class PreparedStatementEx1
{
public static void main(String args[])throws Exception
{
String driverClassName="oracle.jdbc.driver.OracleDriver";
String url="jdbc:oracle:thin:@localhost:1521:xe";
String userName="system";
String password="manager";
//load driver class
Class.forName(driverClassName);
//obtain a connection
Connection conn=DriverManager.getConnection(url,userName,password);
String query="insert into mytable values(?,?,?)";
//step1:Get Prepared Statement
//4.Resultset Example
package com.yellaswamy.jdbcexample;
import java.sql.*;
public class GetAllRows
{
public static void main(String args[])throws
SQLException, ClassNotFoundException
{ //Get Connection
Connection con=prepareConnection ();
// Obtain a Statement
Statement st=con.createStatement ();
String query = "select * from mytable";
//Execute the Query
ResultSet rs=st.executeQuery (query);
System.out.println ("COL1\t\tCOL2\tCOL3");
while (rs.next ())
{
System.out.print (rs.getString ("COL1") + "\t");
System.out.print (rs.getInt ("COL2") + "\t");
System.out.println (rs.getDouble ("COL3")+"\t");
}//while
con.close ();
}//main
public static Connection prepareConnection()
throws SQLException,
ClassNotFoundException
We can have business logic on the database by the use of stored procedures and
functions that will make the performance better because these are precompiled.
Suppose you need the get the age of the employee based on the date of birth, you may
create a function that receives date as the input and returns age of the employee as the
output.
1. The java.sql.CallableStatement is a part of JDBC API that describes a standard abstraction for the
CallableStatement object,implemented by third-party vendor as a part of JDBC driver.
2. The CallableStatement object provides support for both input and output parameters.
The differences between stored procedures and functions are given below:
must not have the return type. must have the return type.
We can call functions from the procedure. Procedure cannot be called from
function.
Procedure supports input and output Function supports only input parameter.
parameters.
Exception handling using try/catch block Exception handling using try/catch can't
can be used in stored procedures. be used in user defined functions.
After registering the OUT parameter type you need to execute the procedure by using execute()
method of CallableStatement object.The execute() method of CallableStatement does not take
any argument.
import java.sql.*;
/**
* @author yellaswamy
*/
public class CallableStatementEx1 {
Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","yellaswamy","yella
swamy");
//Step4
cs.execute();
System.out.println("Account Created");
con.close();
}//main
}//class
package com.yellaswamy.jdbc;
import java.sql.*;
/**
* @author yellaswamy
*/
public class CallableStatementEx2 {
public static void main(String s[]) throws Exception {
Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","yellaswamy","yellas
wamy");
cs.setInt(1, Integer.parseInt(s[0]));
cs.registerOutParameter(2, Types.DOUBLE);
cs.execute();
con.close();
}//main
}//class
OUTPUT:
Applications use the DataSource and RowSet APIs directly, but the connection pooling and
distributed transaction APIs are used internally by the middle-tier infrastructure.
These are the main advantages of using a DataSource object to make a connection:
Changes can be made to a data source's properties, which means that it is not necessary to
make changes in application code when something about the data source or driver
changes.
Connection and Statement pooling and distributed transactions are available through a
DataSource object that is implemented to work with the middle-tier infrastructure.
Connections made through the DriverManager do not have connection and statement
pooling or distributed transaction capabilities.
A logical name for the data source is registered with a naming service that uses the Java Naming
and Directory InterfaceTM (JNDI) API, usually by a system administrator or someone performing
the duties of a system administrator. An application can retrieve the DataSource object it wants
by doing a lookup on the logical name that has been registered for it. The application can then
use the DataSource object to create a connection to the physical data source it represents.
Connection pooling is totally transparent. It is done automatically in the middle tier of a Java EE
configuration, so from an application's viewpoint, no change in code is required. An application
simply uses the DataSource.getConnection method to get the pooled connection and uses it
the same way it uses any Connection object.
ConnectionPoolDataSource
PooledConnection
ConnectionEvent
ConnectionEventListener
StatementEvent
StatementEventListener
The connection pool manager, a facility in the middle tier of a three-tier architecture, uses these
classes and interfaces behind the scenes. When a ConnectionPoolDataSource object is called
on to create a PooledConnection object, the connection pool manager will register as a
ConnectionEventListener object with the new PooledConnection object. When the
connection is closed or there is an error, the connection pool manager (being a listener) gets a
notification that includes a ConnectionEvent object.
If the connection pool manager supports Statement pooling, for PreparedStatements, which
can be determined by invoking the method DatabaseMetaData.supportsStatementPooling,
the connection pool manager will register as a StatementEventListener object with the new
PooledConnection object. When the PreparedStatement is closed or there is an error, the
connection pool manager (being a listener) gets a notification that includes a StatementEvent
object.
XADataSource
XAConnection
These interfaces are used by the transaction manager; an application does not use them directly.
The XAConnection interface is derived from the PooledConnection interface, so what applies
to a pooled connection also applies to a connection that is part of a distributed transaction. A
transaction manager in the middle tier handles everything transparently. The only change in
application code is that an application cannot do anything that would interfere with the
transaction manager's handling of the transaction. Specifically, an application cannot call the
methods Connection.commit or Connection.rollback, and it cannot set the connection to be
in auto-commit mode (that is, it cannot call Connection.setAutoCommit(true)).
Rowsets
The RowSet interface works with various other classes and interfaces behind the scenes. These
can be grouped into three categories.
1. Event Notification
o RowSetListener
A RowSet object is a JavaBeansTM component because it has properties and
participates in the JavaBeans event notification mechanism. The RowSetListener
interface is implemented by a component that wants to be notified about events
that occur to a particular RowSet object. Such a component registers itself as a
listener with a rowset via the RowSet.addRowSetListener method.
When the RowSet object changes one of its rows, changes all of it rows, or moves
its cursor, it also notifies each listener that is registered with it. The listener reacts
by carrying out its implementation of the notification method called on it.
The RowSet interface may be implemented in any number of ways, and anyone may write an
implementation. Developers are encouraged to use their imaginations in coming up with new
ways to use rowsets.