0% found this document useful (0 votes)
7 views

JDBC

JDBC, or Java Database Connectivity, is an API that enables Java applications to interact with various databases through a set of interfaces and classes. It supports both two-tier and three-tier architectures for database access and includes different types of drivers for connecting to databases, such as JDBC-ODBC bridge drivers and thin drivers. The document outlines the components, architecture, and steps required to connect a Java application to a database, particularly focusing on Oracle databases.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

JDBC

JDBC, or Java Database Connectivity, is an API that enables Java applications to interact with various databases through a set of interfaces and classes. It supports both two-tier and three-tier architectures for database access and includes different types of drivers for connecting to databases, such as JDBC-ODBC bridge drivers and thin drivers. The document outlines the components, architecture, and steps required to connect a Java application to a database, particularly focusing on Oracle databases.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 21

What is JDBC?

The term JDBC stands for Java Database Connectivity. JDBC is a


specification from Sun microsystems. JDBC is an API(Application
programming interface) in Java that helps users to interact or
communicate with various databases.

The classes and interfaces of JDBC API allow the application to send the
request to the specified database.

Using JDBC, we can write programs required to access databases. JDBC


and the database driver are capable of accessing databases and
spreadsheets. JDBC API is also helpful in accessing the enterprise data
stored in a relational database(RDB).

Purpose of JDBC
There are some enterprise applications created using the JAVA
EE(Enterprise Edition) technology. These applications need to interact
with databases to store application-specific information.

Interacting with the database requires efficient database connectivity,


which we can achieve using ODBC(Open database connectivity) driver.
We can use this ODBC Driver with the JDBC to interact or communicate
with various kinds of databases, like Oracle, MS Access, Mysql, and SQL,
etc.

Applications of JDBC
JDBC is fundamentally a specification that provides a complete set of
interfaces. These interfaces allow for portable access to an underlying
database.

We can use Java to write different types of executables, such as:

 Java Applications
 Java Applets
 Enterprise JavaBeans (EJBs)
 Java Servlets
 Java ServerPages (JSPs)
All these different executables can use a JDBC driver to access a
database, and take advantage of the stored data. JDBC provides similar
capabilities as ODBC by allowing Java programs to contain database-
independent code.

The JDBC 4.0 Packages


There are two primary packages for JDBC 4.0: java.sql and javax.sql.
JDBC 4.0 is the latest JDBC version at the time of writing this article.
These packages offer the main classes for interacting with data sources.
The new features in these packages include changes in the following
areas:

 Automatic database driver loading.


 Exception handling improvements.
 National character set support.
 SQL ROWID access.
 Enhanced BLOB/CLOB functionality.
 Connection and statement interface enhancements.
 SQL 2003 XML data type support.
 Annotations.
Components of JDBC

There are mainly four main components of JDBC. These components help us to interact with
a database. The components of JDBC are as follows:

1. JDBC API: The JDBC API provides various classes, methods, and interfaces that are
helpful in easy communication with the database. It also provides two packages that contain
the Java SE(Standard Edition) and Java EE(Enterprise Edition) platforms to exhibit the
WORA(write once run everywhere) capabilities.
There is also a standard in JDBC API to connect a database to a client application.

2. JDBC Driver Manager: The Driver Manager of JDBC loads database-specific drivers in
an application. This driver manager establishes a connection with a database. It also makes a
database-specific call to the database so that it can process the user request.

3. JDBC Test suite: The Test Suite of JDBC helps to test the operation such as insertion,
deletion, updation that the JDBC Drivers perform.

4. JDBC-ODBC Bridge Drivers: The JDBC-ODBC Bridge Driver connects the database
drivers to the database. This bridge driver translates the JDBC method call to the ODBC
method call. It uses a package in which there is a native library to access ODBC
characteristics.
JDBC Driver
JDBC Driver is a software component that enables java application to interact with the
database. There are 4 types of JDBC drivers:
1. JDBC-ODBC bridge driver
2. Native-API driver (partially java driver)
3. Network Protocol driver (fully java driver)
4. Thin driver (fully java driver)

1) JDBC-ODBC bridge driver


The JDBC-ODBC bridge driver uses ODBC driver to connect to the database. The JDBC-
ODBC bridge driver converts JDBC method calls into the ODBC function calls. This is now
discouraged because of thin driver.

In Java 8, the JDBC-ODBC Bridge has been removed.

Oracle does not support the JDBC-ODBC Bridge from Java 8. Oracle
recommends that you use JDBC drivers provided by the vendor of your
database instead of the JDBC-ODBC Bridge.

Advantages:

o easy to use.
o can be easily connected to any database.

Disadvantages:

o Performance degraded because JDBC method call is converted into the


ODBC function calls.
o The ODBC driver needs to be installed on the client machine.

2) Native-API driver

The Native API driver uses the client-side libraries of the database. The driver converts
JDBC method calls into native calls of the database API. It is not written entirely in java.

Advantage:

o performance upgraded than JDBC-ODBC bridge driver.

Disadvantage:

o The Native driver needs to be installed on the each client machine.


o The Vendor client library needs to be installed on client machine.
3) Network Protocol driver
The Network Protocol driver uses middleware (application server) that
converts JDBC calls directly or indirectly into the vendor-specific database
protocol. It is fully written in java.

Advantage:

o No client side library is required because of application server that can


perform many tasks like auditing, load balancing, logging etc.

Disadvantages:

o Network support is required on client machine.


o Requires database-specific coding to be done in the middle tier.
o Maintenance of Network Protocol driver becomes costly because it
requires database-specific coding to be done in the middle tier.

4) Thin driver

The thin driver converts JDBC calls directly into the vendor-specific database protocol.
That is why it is known as thin driver. It is fully written in Java language.

Advantage:

o Better performance than all other drivers.


o No software is required at client side or server side.

Disadvantage:

o Drivers depend on the Database.

Architecture of JDBC
The following figure shows the JDBC architecture:
Description of the Architecture:
1. Application: Application in JDBC is a Java applet or a Servlet that communicates with a data source.
2. JDBC API: JDBC API provides classes, methods, and interfaces that allow Java programs to execute
SQL statements and retrieve results from the database. Some important classes and interfaces defined
in JDBC API are as follows:
 DriverManager
 Driver
 Connection
 Statement
 PreparedStatement
 CallableStatement
 ResultSet
 SQL data

3. Driver Manager: The Driver Manager plays an important role in the JDBC architecture. The Driver
manager uses some database-specific drivers that effectively connect enterprise applications to
databases.

4. JDBC drivers: JDBC drivers help us to communicate with a data source through JDBC. We need a
JDBC driver that can intelligently interact with the respective data source.
Types of JDBC Architecture
There are two types of processing models in JDBC architecture: two-tier and three-tier. These models help us to
access a database. They are:

1. Two-tier model
In this model, a Java application directly communicates with the data source. JDBC driver provides
communication between the application and the data source. When a user sends a query to the data source, the
answers to those queries are given to the user in the form of results.

We can locate the data source on a different machine on a network to which a user is connected. This is called a
client/server configuration, in which the user machine acts as a client, and the machine with the data source acts
as a server.

2. Three-tier model
In the three-tier model, the query of the user queries goes to the middle-tier services. From the middle-tier
service, the commands again reach the data source. The results of the query go back to the middle tier.

From there, it finally goes to the user. This type of model is beneficial for management information system
directors.

JDBC Architecture
The JDBC API supports both two-tier and three-tier processing models for database access.

Figure 1: Two-tier Architecture for Data Access.

In the two-tier model, a Java applet or application talks directly to the data source. This
requires a JDBC driver that can communicate with the particular data source being accessed.
A user's commands are delivered to the database or other data source, and the results of those
statements are sent back to the user. The data source may be located on another machine to
which the user is connected via a network. This is referred to as a client/server configuration,
with the user's machine as the client, and the machine housing the data source as the server.
The network can be an intranet, which, for example, connects employees within a
corporation, or it can be the Internet.

In the three-tier model, commands are sent to a "middle tier" of services, which then sends
the commands to the data source. The data source processes the commands and sends the
results back to the middle tier, which then sends them to the user. MIS directors find the
three-tier model very attractive because the middle tier makes it possible to maintain control
over access and the kinds of updates that can be made to corporate data. Another advantage is
that it simplifies the deployment of applications. Finally, in many cases, the three-tier
architecture can provide performance advantages.
Figure 2: Three-tier Architecture for Data Access.

Until recently, the middle tier has often been written in languages such as C or C++, which offer fast
performance. However, with the introduction of optimizing compilers that translate Java bytecode into efficient
machine-specific code and technologies such as Enterprise JavaBeans™, the Java platform is fast becoming the
standard platform for middle-tier development. This is a big plus, making it possible to take advantage of Java's
robustness, multithreading, and security features.
With enterprises increasingly using the Java programming language for writing server code, the JDBC API is
being used more and more in the middle tier of a three-tier architecture. Some of the features that make JDBC a
server technology are its support for connection pooling, distributed transactions, and disconnected rowsets. The
JDBC API is also what allows access to a data source from a Java middle tier.

Steps of Java Database Connectivity


There are 5 steps to connect any java application with the database using JDBC. These
steps are as follows:

o Register the Driver class


o Create connection
o Create statement
o Execute queries
o Close connection
1) Register the driver class
The forName() method of Class class is used to register the driver class. This method is
used to dynamically load the driver class.

Syntax of forName() method

1. public static void forName(String className)throws ClassNotFou


ndException
Note: Since JDBC 4.0, explicitly registering the driver is optional. We just need to
put vender's Jar in the classpath, and then JDBC driver manager can detect and
load the driver automatically.

Example to register the OracleDriver class


Here, Java program is loading oracle driver to esteblish database
connection.

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

2) Create the connection object


The getConnection() method of DriverManager class is used to establish connection with
the database.

Syntax of getConnection() method

1. 1) public static Connection getConnection(String url)throws SQLE


xception
2. 2) public static Connection getConnection(String url,String name,String p
assword)
3. throws SQLException

Example to establish connection with the Oracle


database

1. Connection con=DriverManager.getConnection(
2. "jdbc:oracle:thin:@localhost:1521:xe","system","password");

3) Create the Statement object

The createStatement() method of Connection interface is used to create statement. The


object of statement is responsible to execute queries with the database.

Syntax of createStatement() method

1. public Statement createStatement()throws SQLException

Example to create the statement object

1. Statement stmt=con.createStatement();

4) Execute the query


The executeQuery() method of Statement interface is used to execute queries to the
database. This method returns the object of ResultSet that can be used to get all the
records of a table.

Syntax of executeQuery() method

1. public ResultSet executeQuery(String sql)throws SQLException


Example to execute query

1. ResultSet rs=stmt.executeQuery("select * from emp");


2.
3. while(rs.next()){
4. System.out.println(rs.getInt(1)+" "+rs.getString(2));
5. }

5) Close the connection object

By closing connection object statement and ResultSet will be closed automatically. The
close() method of Connection interface is used to close the connection.

Syntax of close() method

1. public void close()throws SQLException

Example to close connection

1. con.close();

It avoids explicit connection closing step.

Java Database Connectivity with Oracle


To connect java application with the oracle database, we need to follow 5
following steps. In this example, we are using Oracle 10g as the database. So
we need to know following information for the oracle database:
1. Driver class: The driver class for the oracle database
is oracle.jdbc.driver.OracleDriver.
2. Connection URL: The connection URL for the oracle10G database
is jdbc:oracle:thin:@localhost:1521:xe where jdbc is the API, oracle
is the database, thin is the driver, localhost is the server name on which
oracle is running, we may also use IP address, 1521 is the port number
and XE is the Oracle service name. You may get all these information
from the tnsnames.ora file.
3. Username: The default username for the oracle database is system.
4. Password: It is the password given by the user at the time of installing
the oracle database.

Create a Table

Before establishing connection, let's first create a table in oracle database.


Following is the SQL query to create a table.
1. create table emp(id number(10),name varchar2(40),age number(3));

and insert few records in it.

For example,

Here I have inserted 3 rows in the table emp

Example program to Connect Java Application with


Oracle database
In this example, we are connecting to an Oracle database and getting data from emp table.
Here, system and student are the username and password of the Oracle database.

import java.sql.*;
class OracleCon{
public static void main(String args[]){
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","student");

Statement stmt=con.createStatement();

ResultSet rs=stmt.executeQuery("select * from emp");


while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2)+"
"+rs.getString(3));

con.close();

}catch(Exception e){ System.out.println(e);}

}
}

The above example will fetch all the records of emp table.

To connect java application with the Oracle database ojdbc14.jar file is required to be loaded.

download the jar file ojdbc14.jar

now,

1. paste the ojdbc14.jar file in jre/lib/ext folder


2. set classpath

paste the ojdbc14.jar file in JRE/lib/ext folder:


Firstly, search the ojdbc14.jar file then go to JRE/lib/ext folder and paste the jar file here
set classpath:

How to set the permanent classpath:


Go to environment variable then click on new tab. In variable name write classpath and
in variable value paste the path to ojdbc14.jar by appending ojdbc14.jar;.; as

C:\oraclexe\app\oracle\product\10.2.0\server\jdbc\lib\ojdbc14.jar; C:\Program Files\Java\


jre1.8.0_45\lib\ext\ojdbc14.jar

Now execute the java program…This program will now display all
the content of the table we created in oracle database.
ResultSet interface
The object of ResultSet maintains a cursor pointing to a row of a table.
Initially, cursor points to before the first row.

By default, ResultSet object can be moved forward only and it is not updatable.

But we can make this object to move forward and backward direction by
passing either TYPE_SCROLL_INSENSITIVE or TYPE_SCROLL_SENSITIVE in
createStatement(int,int) method as well as we can make this object as
updatable by:

1. Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INS


ENSITIVE,
2. ResultSet.CONCUR_UPDATABLE);

Commonly used methods of ResultSet interface

1) public boolean next(): is used to move the cursor to the one row next from
the current position.

2) public boolean is used to move the cursor to the one row previous
previous(): from the current position.
3) public boolean first(): is used to move the cursor to the first row in result
set object.

4) public boolean last(): is used to move the cursor to the last row in result
set object.

5) public boolean is used to move the cursor to the specified row


absolute(int row): number in the ResultSet object.

6) public boolean is used to move the cursor to the relative row


relative(int row): number in the ResultSet object, it may be positive or
negative.

7) public int getInt(int is used to return the data of specified column index
columnIndex): of the current row as int.

8) public int getInt(String is used to return the data of specified column name
columnName): of the current row as int.

9) public String is used to return the data of specified column index


getString(int of the current row as String.
columnIndex):

10) public String is used to return the data of specified column name
getString(String of the current row as String.
columnName):

Example of Scrollable ResultSet


Let’s see the simple example of ResultSet interface to retrieve the data of
3rd row.

1. import java.sql.*;
2. class FetchRecord{
3. public static void main(String args[])throws Exception{
4.
5. Class.forName("oracle.jdbc.driver.OracleDriver");
6. Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhos
t:1521:xe","system","oracle");
7. Statement stmt=con.createStatement(ResultSet.TYPE_SCROLL_SEN
SITIVE,ResultSet.CONCUR_UPDATABLE);
8. ResultSet rs=stmt.executeQuery("select * from emp765");
9.
10.//getting the record of 3rd row
11. rs.absolute(3);
12.System.out.println(rs.getString(1)+" "+rs.getString(2)+" "+rs.getString(3)
);
13.
14.con.close();
15. }}

Java DatabaseMetaData interface


DatabaseMetaData interface provides methods to get meta data of a
database such as database product name, database product version,
driver name, name of total number of tables, name of total number of
views etc.

Commonly used methods of DatabaseMetaData


interface
o public String getDriverName()throws SQLException: it returns the
name of the JDBC driver.
o public String getDriverVersion()throws SQLException: it returns the
version number of the JDBC driver.
o public String getUserName()throws SQLException: it returns the
username of the database.
o public String getDatabaseProductName()throws SQLException: it
returns the product name of the database.
o public String getDatabaseProductVersion()throws SQLException: it
returns the product version of the database.
o public ResultSet getTables(String catalog, String schemaPattern,
String tableNamePattern, String[] types)throws SQLException: it
returns the description of the tables of the specified catalog. The table
type can be TABLE, VIEW, ALIAS, SYSTEM TABLE, SYNONYM etc.

How to get the object of DatabaseMetaData:


The getMetaData() method of Connection interface returns the object of
DatabaseMetaData. Syntax:

1. public DatabaseMetaData getMetaData()throws SQLException

Simple Example of DatabaseMetaData interface :

1. import java.sql.*;
2. class Dbmd{
3. public static void main(String args[]){
4. try{
5. Class.forName("oracle.jdbc.driver.OracleDriver");
6.
7. Connection con=DriverManager.getConnection(
8. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
9. DatabaseMetaData dbmd=con.getMetaData();
10.
11. System.out.println("Driver Name: "+dbmd.getDriverName());
12.System.out.println("Driver Version: "+dbmd.getDriverVersion());
13. System.out.println("UserName: "+dbmd.getUserName());
14.System.out.println("Database Product Name: "+dbmd.getDatabaseProduct
Name());
15. System.out.println("Database Product Version: "+dbmd.getDa
tabaseProductVersion());
16.
17. con.close();
18.}catch(Exception e){ System.out.println(e);}
19. }
20.}
Output:Driver Name: Oracle JDBC Driver
Driver Version: 10.2.0.1.0XE
Database Product Name: Oracle
Database Product Version: Oracle Database 10g Express Edition
Release 10.2.0.1.0 -Production

Example of DatabaseMetaData interface that prints total


number of tables :

1. import java.sql.*;
2. class Dbmd2{
3. public static void main(String args[]){
4. try{
5. Class.forName("oracle.jdbc.driver.OracleDriver");
6.
7. Connection con=DriverManager.getConnection(
8. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
9.
10.DatabaseMetaData dbmd=con.getMetaData();
11. String table[]={"TABLE"};
12.ResultSet rs=dbmd.getTables(null,null,null,table);
13.
14.while(rs.next()){
15. System.out.println(rs.getString(3));
16.}
17.
18.con.close();
19.
20.}catch(Exception e){ System.out.println(e);}
21.
22.}
23. }

Example of DatabaseMetaData interface that prints total


number of views :

1. import java.sql.*;
2. class Dbmd3{
3. public static void main(String args[]){
4. try{
5. Class.forName("oracle.jdbc.driver.OracleDriver");
6.
7. Connection con=DriverManager.getConnection(
8. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
9.
10.DatabaseMetaData dbmd=con.getMetaData();
11. String table[]={"VIEW"};
12.ResultSet rs=dbmd.getTables(null,null,null,table);
13.
14.while(rs.next()){
15. System.out.println(rs.getString(3));
16.}
17.
18.con.close();
19.
20.}catch(Exception e){ System.out.println(e);}
21.
22.}
23. }

You might also like