Advance Java Programming(225
5.INTERACTING
WITH DATABASE
(12 MARKS)
Miss.P.S.Dungarwal
Lecturer in CM
Department.
SHHJB Polytechnic,
Chandwad.
ODBC
ODBC stands for Open Database
Connectivity
A standard or open application
programming interface (API) for
accessing a database.
ODBC provides a C interface for
database access on Windows
environment.
Miss.P.S.Dungarwal 2
JDBC
JDBC stands
for Java Database Connectivity.
It is a standard Java API for
connecting programs written in
Java to the data in relational
databases.
JDBC works with Java on a
variety of platforms, such as
Windows, Mac OS, and the
various versions of UNIX.
Miss.P.S.Dungarwal 3
JDBC DRIVER
JDBC Driver is a software component that
enables java application to interact with
the database. There are 4 types of JDBC
drivers:
JDBC-ODBC bridge driver
Native-API driver (partially java driver)
JDBC-Net pure Java/ Network-Protocol
driver (fully java driver)
Pure Java Driver /Thin driver / Database-
Protocol driver(fully java driver)
Miss.P.S.Dungarwal 4
JDBC-ODBC BRIDGE DRIVER
The JDBC type 1 driver, also known as the 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.
Miss.P.S.Dungarwal 5
NATIVE API DRIVER
The JDBC type 2 driver, also known as
the 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.
Miss.P.S.Dungarwal 6
JDBC-NET PURE JAVA DRIVER
The JDBC type 3 driver, also known as the
Pure Java driver for database middleware. It
is a database driver implementation which
makes use of a middle tier between the calling
program and the database.
The middle-tier (application server)
converts JDBC calls directly or indirectly into a
vendor-specific database protocol. It is fully
written in java.
Miss.P.S.Dungarwal 7
THIN DRIVER
The JDBC type 4 driver, also known as the Direct to
Database Pure Java Driver, is a database driver
implementation that converts JDBC calls directly into a
vendor specific database protocol.
That is why it is known as thin driver. It is fully written in
Java language.
Miss.P.S.Dungarwal 8
JDBC TWO TIER MODEL
In a two-tier model, a Java application
communicates directly with the database, via the
JDBC driver.
Miss.P.S.Dungarwal 9
JDBC THREE TIER MODEL
In a three-tier model, a Java application
communicates with a middle tier component
that functions as an application server. The
application server talks to a given database
using JDBC.
Miss.P.S.Dungarwal 10
COMMON JDBC COMPONENTS
The JDBC API provides the following
interfaces and classes −
DriverManager Class
Driver Interface
Connection Interface
Statement Interface
ResultSet Interface
Miss.P.S.Dungarwal 11
COMMON JDBC COMPONENTS
DriverManager Class
The DriverManager class acts as an
interface between user and drivers.
It keeps track of the drivers that are
available and handles establishing a
connection between a database and the
appropriate driver.
The DriverManager class maintains a list of
Driver classes that have registered
themselves by calling the method
DriverManager.registerDriver().
Miss.P.S.Dungarwal 12
Commonly used methods of
DriverManager class
Method Description
public static void is used to register the given
driver with DriverManager.
registerDriver( Driver driver);
public static void is used to deregister the given
driver (drop the driver from the
list) with DriverManager.
deregisterDriver( Driver driver);
public static Connection is used to establish the
connection with the specified
url.
getConnection ( String url);
public static Connection is used to establish the
getConnection( String url, String connection with the specified
url, username and password.
userName, String password);
Miss.P.S.Dungarwal 13
DRIVER INTERFACE
This interface handles the
communications with the database
server.
You will very rarely interact directly with
Driver objects.
Instead, you use DriverManager objects,
which manages objects of this type.
Miss.P.S.Dungarwal 14
CONNECTION INTERFACE
A Connection is the session between java
application and database.
The Connection interface provide many methods
for transaction management like commit(),
rollback() etc.
When getConnection() method is called, it
returns a connection object.
Connection
con=DriverManager.getConnection(URL);
Miss.P.S.Dungarwal 15
Commonly used methods of Connection
interface
Method Description
creates a statement
public Statement object that can be
used to execute SQL
createStatement(); queries.
public void It is used to set the
setAutoCommit(bo commit status.
default it is true.
By
olean status);
It saves the changes
public void made since the
previous
commit(); commit/rollback
permanent.
Drops all changes
public void made since the
previous
rollback(); commit/rollback.
closes the connection and
Releases a JDBC resources
public void close(); immediately.
Miss.P.S.Dungarwal 16
STATEMENT INTERFACE
The Statement interface provides methods
to execute queries with the database.
It provides factory method to get the object of
ResultSet.
Miss.P.S.Dungarwal 17
Commonly used methods of Statement interface
Method Description
public ResultSet
used to execute SELECT query.
executeQuery(String It returns the object of ResultSet.
sql);
public int used to execute specified query,
executeUpdate(String it may be create, drop, insert,
sql); update, delete etc.
public boolean used to execute queries that may
execute(String sql); return multiple results.
public int[] used to execute batch of
executeBatch(); commands.
void close() Miss.P.S.Dungarwal
Close the statement object
18
RESULTSET INTERFACE
A ResultSet object provides access to a
table of data.
ResultSet object is usually generated by
executing a statement.
The object of ResultSet maintains a
cursor pointing to a particular row of
data.
Initially, cursor points before the first row.
Miss.P.S.Dungarwal 19
Commonly used methods of ResultSet interface
Method Description
public boolean next(); is used to move the cursor to the one row next
from the current position.
public boolean previous(); is used to move the cursor to the one row
previous from the current position.
public boolean first(); is used to move the cursor to the first row in
result set object.
public boolean last(); is used to move the cursor to the last row in
result set object.
public boolean absolute(int is used to move the cursor to the specified row
number in the ResultSet object.
row);
public int getInt(int is used to return the data of specified column
index of the current row as int.
columnIndex);
public int getInt(String is used to return the data of specified column
name of the current row as int.
columnName);
public String getString(int is used to return the data of specified column
index of the current row as String.
columnIndex);
public String is used to return the data of specified column
name of the current row as String.
getString(String Miss.P.S.Dungarwal 20
CONNECTING TO DATABASE
There are 5 steps to connect any java
application with the database in java
using JDBC. They are as follows:
1. Register the driver class
2. Creating connection
3. Creating statement
4. Executing queries
5. Closing connection
Miss.P.S.Dungarwal 21
1.REGISTER THE DRIVER
CLASS
The Class.forName() method is used to register
the driver class. This method is used to dynamically
load the driver class.
Syntax of forName() method
public static void forName(String className)throws ClassNotFou
ndException
Example to register with JDBC-ODBC
Driver
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Miss.P.S.Dungarwal 22
2. Creating connection
The DriverManager.getConnection()
method is used to establish connection
with the database.
Example establish connection
with Oracle Driver
Connection con =
DriverManager.getConnection
("jdbc:odbc:DemoDB","username","password"
);
Miss.P.S.Dungarwal 23
3. Creating statement
The createStatement() method of
Connection interface is used to create
statement. The object of statement is
responsible to execute queries with the
database.
Example to create the statement
object
Statement stmt=con.createStatement();
Miss.P.S.Dungarwal 24
4. Executing queries
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.
Example to execute query
ResultSet rs=stmt.executeQuery("select * from em
p");
while(rs.next())
{
System.out.println(rs.getInt(1)+" "+rs.getString(2))
;
Miss.P.S.Dungarwal 25
5. Closing connection
By closing connection object statement
and ResultSet will be closed automatically.
The close() method of Connection interface
is used to close the connection.
Example to close connection
con.close();
Miss.P.S.Dungarwal 26
Example to Connect Java
Application with mysql
database
Miss.P.S.Dungarwal 27
import java.sql.*;
class MysqlCon{
public static void main(String args[])
{
Try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://
localhost:3306/Emp","root","root");
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); }
} Miss.P.S.Dungarwal 28
CONNECTION WITH ACCESS
DATABASE
Miss.P.S.Dungarwal 29
import java.sql.*;
public class JdbcAccessTest {
public static void main(String[] args) {
String databaseURL =
"jdbc:ucanaccess://e://Contacts.accdb";
try (
Connection connection =
DriverManager.getConnection(databaseURL)) {
String sql = "INSERT INTO Contacts (Full_Name, Email, Phone)
VALUES (?, ?, ?)";
PreparedStatement preparedStatement =
connection.prepareStatement(sql);
preparedStatement.setString(1, "Rohit");
preparedStatement.setString(2, "[email protected]");
preparedStatement.setString(3, "0919989998");
int row = preparedStatement.executeUpdate();
if (row > 0) {
System.out.println("A row has been inserted
successfully."); Miss.P.S.Dungarwal 30
sql = "SELECT * FROM Contacts";
Statement statement =
connection.createStatement();
ResultSet result = statement.executeQuery(sql);
while (result.next()) {
int id = result.getInt("Contact_ID");
String fullname = result.getString("Full_Name");
String email = result.getString("Email");
String phone = result.getString("Phone");
System.out.println(id + ", " + fullname + ", " + email +
", " + phone);
}
} catch (SQLException ex) {
ex.printStackTrace();
}
}
Miss.P.S.Dungarwal 31