UNIT V
UNIT V
UNIT V
Architecture of JDBC
The JDBC API supports both two-tier and three- tier architecture for database access.
Two-tier Architecture
Two-tier Architecture provides direct communication between Java applications to the database. It
requires a JDBC driver that can help to communicate with the particular database.
Three-tier Architecture
In the three-tier model, commands are sent by the HTML browser to middle services i.e. Java application
which can send the commands to the particular database. The middle tier has been written in C or
C++languages. It can also provide better performance.
JDBC Components
Following are the components of JDBC that help Java application connect with database.
JDBC API
P a g e 1 | 15
UNIT – IVINTERACTING WITH DATABASE
The JDBC provides the various methods and interface for easy communication between Java application
and database.
DriverManager
The DriverManager is a class that manages all database drivers. It loads the specific database drivers in
an application to establish connection with database.
Connection
Connection is an interface that contains all methods for contacting with database.
JDBC Driver
A JDBC driver is set of software components that help a Java application to interact with database. The
JDBC driver implements lots of JDBC classes and interfaces that enable to open connection and interact
with database server.
JDBC-ODBC Bridge
JDBC-ODBC Bridge provides a interface that helps to connect database drivers to the database.
JDBC driver implementations vary because of the wide variety of operating systems and hardware
platforms in which Java operates. Sun has divided the implementation types into four categories, Types
1, 2, 3, and 4, which is explained below −
In a Type 1 driver, a JDBC bridge is used to access ODBC drivers installed on each client machine. Using
ODBC, requires configuring on your system a Data Source Name (DSN) that represents the target
database.
When Java first came out, this was a useful driver because most databases only supported ODBC access
but now this type of driver is recommended only for experimental use or when no other alternative is
available.
P a g e 2 | 15
UNIT – IVINTERACTING WITH DATABASE
The JDBC-ODBC Bridge that comes with JDK 1.2 is a good example of this kind of driver.
In a Type 2 driver, JDBC API calls are converted into native C/C++ API calls, which are unique to the
database. These drivers are typically provided by the database vendors and used in the same manner as
the JDBC-ODBC Bridge. The vendor-specific driver must be installed on each client machine.
If we change the Database, we have to change the native API, as it is specific to a database and they are
mostly obsolete now, but you may realize some speed increase with a Type 2 driver, because it eliminates
ODBC's overhead.
In a Type 3 driver, a three-tier approach is used to access databases. The JDBC clients use standard
network sockets to communicate with a middleware application server. The socket information is then
translated by the middleware application server into the call format required by the DBMS, and forwarded
to the database server.
This kind of driver is extremely flexible, since it requires no code installed on the client and a single
driver can actually provide access to multiple databases.
You can think of the application server as a JDBC "proxy," meaning that it makes calls for the client
application. As a result, you need some knowledge of the application server's configuration in order to
effectively use this driver type.
Your application server might use a Type 1, 2, or 4 driver to communicate with the database,
understanding the nuances will prove helpful.
In a Type 4 driver, a pure Java-based driver communicates directly with the vendor's database through
socket connection. This is the highest performance driver available for the database and is usually
provided by the vendor itself.
This kind of driver is extremely flexible, you don't need to install special software on the client or server.
Further, these drivers can be downloaded dynamically.
P a g e 4 | 15
UNIT – IVINTERACTING WITH DATABASE
MySQL's Connector/J driver is a Type 4 driver. Because of the proprietary nature of their network
protocols, database vendors usually supply type 4 drivers.
If you are accessing one type of database, such as Oracle, Sybase, or IBM, the preferred driver type is 4.
If your Java application is accessing multiple types of databases at the same time, type 3 is the preferred
driver.
Type 2 drivers are useful in situations, where a type 3 or type 4 driver is not available yet for your
database.
The type 1 driver is not considered a deployment-level driver, and is typically used for development and
testing purposes only.
For example:
Class.forName("oracle.jdbc.odbc.JdbcOdbcDriver");
P a g e 5 | 15
UNIT – IVINTERACTING WITH DATABASE
Syntax:
public Statement createStatement( ) throws SQLException
Example:
Statement stmt = con.createStatement();
Syntax:
public ResultSet executeQuery(String sql) throw SQLException
Example
ResultSet rs = stmt.executeQuery("select * from students");
while (rs.next())
{
System.out.println (rs.getInt(1)+" "+rs.getString(2)+" "+rs.getFloat(3));
}
Syntax:
public void close( ) throws SQLException
Example:
con.close( );
Note: We will discuss whole program in JDBC using oracle database with type 4 (Thin) driver.
P a g e 6 | 15
UNIT – IVINTERACTING WITH DATABASE
DriverManager Class
The DriverManager class is responsible for managing the basic service to set of JDBC drivers. It acts
as an interface between Java application and drivers. The DriverManager class will attempt to load the
driver classes referenced in "jdbc.drivers" system property.
The DriverManager class loads the JDBC drivers to the system property.
P a g e 7 | 15
UNIT – IVINTERACTING WITH DATABASE
Methods Description
getDriver(String url) Helps to locate a driver that understands the given
URL.
registerDriver(Driver driver) Used to register the given driver with the
DriverManager class.
static void deregisterDriver(Driver driver) Removes the specified driver from the
DriverManager class.
static Connection getConnection(String url) It creates the connection with the given database
URL.
static Connection getConnection(String url, Establishes the connection with given database
String username, String password) URL with username and password.
Statement Interface
The Statement interface provides the method to execute the database queries. After making a
connection, Java application can interact with database. The Statement interface contains the ResultSet
object.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
P a g e 8 | 15
UNIT – IVINTERACTING WITH DATABASE
import java.sql.Statement;
public class SelectTest
{
public static void main(String[] args) throws Exception
{
Class.forName("oracle.jdbc.OracleDriver");
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","scott","tiger");
Statement st = con.createStatement();
ResultSetrs = st.executeQuery("select * from student");
while(rs.next()!=false)
{
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3)+"
"+rs.getString(4));
}
rs.close();
st.close();
con.close();
}
}
PreparedStatement Interface
Note: All the parameter are represented by "?" symbol and each parameter is referred to by its
origin position.
import java.sql.*;
class PreparedStatDemo
{
public static void main(String args[])
{
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con =
P a g e 9 | 15
UNIT – IVINTERACTING WITH DATABASE
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","username", "password");
PreparedStatementps = con.prepareStatement("insert into Student values(?, ?, ?)");
ps.setInt(1, 101);
ps.setString(2, "Surendra");
ps.setString(3, "MCA");
ps.executeUpdate();
con.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
CallableStatement Interface
The CallableStatement interface is used to execute the SQL stored procedure in a database. The JDBC
API provides stored procedures to be called in a standard way for all RDBMS.
A stored procedure works like a function or method in a class. The stored procedure makes the
performance better because these are precompiled queries.
For example:
CallableStatementcallableStatement = con.prepareCall("{call procedures(?,?)}");
// ProcedureDemo.java
P a g e 10 | 15
UNIT – IVINTERACTING WITH DATABASE
import java.sql.*;
classProcedureDemo
{
public static void main(String args[])
{
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","scott","tiger");
CallableStatementstmt = con.prepareCall("{call insertStudents(?, ?) }");
stmt.setInt(1, 101);
stmt.setString(2, Vinod);
stmt.setString(3, BE);
stmt.execute();
System.out.println("Record inserted successfully");
con.close();
stmt.close();
}
catch(Execption e)
{
e.printStackTrace();
}
}
}
Note: The ProcedureDemo.java file inserts the record in Students table in Oracle database by
use of stored procedure.
ResultSet Interface
The result of the query after execution of database statement is returned as table of data
according to rows and columns. This data is accessed using the ResultSet interface.
A default ResultSet object is not updatable and the cursor moves only in forward direction.
Example
P a g e 11 | 15
UNIT – IVINTERACTING WITH DATABASE
Or
Methods Description
public boolean absolute(int row) Moves the cursor to the specified row in the ResultSet object.
public void beforeFirst( ) It moves the cursor just before the first row i.e. front of the
ResultSet.
public void afterLast() Moves the cursor to the end of the ResultSet object, just after the
last row.
public boolean first() Moves the cursor to first value of ResultSet object.
public boolean last( ) Moves the cursor to the last row of the ResultSet object.
public boolean previous ( ) Just moves the cursor to the previous row in the ResultSet
object.
public boolean next( ) It moves the curser forward one row from its current position.
public intgetInt(intcolIndex) It retrieves the value of the column in current row as int in given
ResultSet object.
public String getString( It retrieves the value of the column in current row as int in given
intcolIndex) ResultSet object.
public void relative(int rows) It moves the cursor to a relative number of rows.
P a g e 12 | 15
UNIT – IVINTERACTING WITH DATABASE
MCQ’s on JDBC
P a g e 14 | 15
UNIT – IVINTERACTING WITH DATABASE
P a g e 15 | 15