Interacting With Database
Interacting With Database
Unit-5
Interacting with Database
By
Prof. Mane D.S.
H.O.D. Computer Engineering Department
S.P.M. Polytechnic, Kumathe
JDBC Architecture
The JDBC Architecture can be classified
into two layers:
1. JDBC Application Layer
2. JDBC Driver Layer
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.
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.
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)
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.
Advantages:
• easy to use.
• can be easily connected to any database.
Disadvantages:
• Performance degraded because JDBC method
call is converted into the ODBC function calls.
• The ODBC driver needs to be installed on the
client machine.
Native API driver
• The JDBC type 2 driver, also known as the Native-API driver
• The Native API driver uses the Local native libraries
provided by the database vendors to access databases.
• The JDBC driver maps the JDBC calls to the
native method calls, which are passed to the
native call level interface(CLI).
• This interface consists of functions written
in C to access database.
• To use the Type-2 driver CLI needs to be
loaded on the client computer as opposed to the
JDBC-ODBC bridge driver, the Native API java
driver does not have an ODBC intermediate layer.
As a result, this driver has a better performance
than the JDBC-ODBC bridge driver.
• This driver is used for Network based
applications.
Advantage:
• performance upgraded than JDBC-ODBC
bridge driver.
Disadvantage:
• The Native driver needs to be installed on the
each client machine.
• The Vendor client library needs to be installed
on client machine.
Advanced Java Programming
Unit-5
Interacting with Database
By
Prof. Mane D.S.
H.O.D. Computer Engineering Department
S.P.M. Polytechnic, Kumathe
Recap
JDBC Architecture
JDBC Drivers:
a) JDBC-ODBC Bridge Driver.
b) Native API Partly Java Driver.
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.
• The client portion consists of pure java
functions and the server portion contains java
and native methods.
• The java applications sends JDBC calls to
the JDBC-Net pure java driver client portion,
which in turn translate JDBC calls into
database calls.
• The database calls are sent to the server
portion of the JDBC-Net pure java driver that
forward the request to the database.
• when you use the JDBC-Net pure java
driver native libraries are loaded on the
server.
Advantage:
• No client side library is required because of
application server that can perform many tasks
like auditing, load balancing, logging etc.
Disadvantages:
• Network support is required on client machine.
• Requires database-specific coding to be done in
the middle tier.
• Maintenance of Network Protocol driver
becomes costly because it requires database-
specific coding to be done in the middle tier.
.
Native Protocol Pure Java Driver/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.
• As opposed to the other JDBC
driver, you do not require to install any
vender specific libraries to use the Type
4 driver.
• Data direct technologies provides
Type 4 driver for various databases such
as MS SQL server, DB2.
• This driver is usually used for
enterprise applications.
Advantage:
• Better performance than all other drivers.
• No software is required at client side or server
side.
Disadvantage:
• Drivers depend on the Database.
.
JDBC two tier model
• In a two-tier model, a Java application communicates
directly with the database, via the JDBC driver.
.
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.
.
Advanced Java Programming
Unit-5
Interacting with Database
By
Prof. Mane D.S.
H.O.D. Computer Engineering Department
S.P.M. Polytechnic, Kumathe
Recap
JDBC Drivers:
c) JDBC-Net pure Java Driver.
d) Native-Protocol pure java Driver/ Thin
Driver.
JDBC API
• The JDBC API provides the following interfaces
and classes defined in java.sql & javax.sql
packages−
• DriverManager Class
• Driver Interface
• Connection Interface
• Statement Interface
• ResultSet Interface
• SQL Exception class
.
Steps to Follow to connect with database &
retrieving results
1. Load a driver.
2. Connect to database.
.
Create an object of the connection interface
to establish a connection of java application with a
database.
The DriverManager class provides the
getConnection() method to create connection
object.
1. Connection getConnection(String <url>):
The syntax for a JDBC url that is passed as a
parameter to getConnection() method is:
<protocol>:<subprotocol>:<subname>
A JDBC url has following three components:
1) protocol name:
Indicates the name of the protocol that is
used to access a database.
2) sub protocol name:
Indicates the mechanism to retrive data from a
database.
3) subname:
Indicate the Data Source Name(DSN) that
contains database information such as name of
database, Location of the database server, user
name, password to access database server.
e.g.
String url=“jdbc:odbc:MydataSource”;
Connection con=DriverManager.getConnection(url);
2. Connection getConnection(String<url>,
String<username>, String<password>):
Accepts a JDBC url of a database. It also accepts
the user name and password of the authorized
database server.
e.g.
String url=“jdbc:odbc:MyDataSource”;
Connection con=DriverManager.getConnection(url,
“new user”, “new password”);
3. Connection getConnection(String<url>,
properties<properties>):
Accepts the JDBC url of a database and properties
parameter which specify information such as user
name and password in the properties object using
setProperty() method.
e.g.
String url=“jdbc:odbc:MyDataSource”;
Properties p=new Properties();
p.setProperty(“user”,”new user”);
p.setProperty(“password”,new password”);
Connection con=DriverManager.getConnection(url,p);
Commonly used methods of DriverManager class
Method Description
public static void registerDriver(Driver driver); is used to register the given driver
with DriverManager.
1. Load a driver.
2. Connect to database.
.
The Connection object provides the
createStatement() method to create a statement
object.
e.g.
Connection
con=DriverManager.getConnection(“jdbc:odbc:MyD
ataSource”,”new user”,”new password”);
Statement stmt=con.createStatement();
1. ResultSet executeQuery(String str):
Execute an SQL statement and return a
single object of the type ResultSet.
The executeQuery() method should be
used when we need to retrive data from a
database table using the SELECT statement.
The Syntax is:
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery(<SQL stmt>);
The stmt is a reference to the object of
Statement interface. The executeQuery()
method execute an SQL statement and result
retrived from database is stored in rs the
2. int executeUpdate(String str):
Executes the SQL statements and returns
the number of data rows that are affected after
processing the SQL statement.
When we need to modify data in a database
table using the Data Manipulation
Language(DML) statements INSERT, DELETE and
UPDATE.
The Syntax is:
Statement stmt=con.createStatement();
int count=stmt.executeUpdate(<SQL stmt>);
The executeUpdate() method executes an
SQL stmt. and number of rows affected in a
3. boolean execute(String str):
Executes an SQL statements and returns
a boolean value.
We can use this method when the type
of SQL statement passed as a parameter is
not known or when the statements being
executed returns a resultset or an update
count.
The execute() method returns true if the
result of the SQL statement is an object of
ResultSet and false if it is an update count.
e.g.
Statement stmt=con.createStatement();
Commonly used methods of Statement interface
Method Description
public boolean execute(String sql); used to execute queries that may return
multiple results.
.
Accessing ResultSet Interface
• ResultSet Interface
When we execute a query to retrive data
from a table using a Java Application, the output
of query is stored in a ResultSet object in tabular
format.
The ResultSet object maintains a cursor that
moves in the forward direction only.
As a result it moves from the first row to the
last row in the ResultSet.
Types of ResultSet:
1. Read only:
Allows to only read the rows in a ResultSet
object.
2. Forward only:
Allow to move the resultset cursor from first row
to last row in forward direction only.
3. Scrollable:
Allow to move the resultset cursor forward and
backward through the resultset.
4. Updatable:
Allow to update the resultset rows retrived from
a database table.
we can specify the type of ResultSet object using
the createStatement() method of connection interface.
Methods of ResultSet Interface:
.
Methods of Prepared Statement
interface
The preparedStatement interface inherits
the following methods to execute SQL stmt.
From the Statement interface.
1. ResultSet executeQuery():
Executes a SELECT statement and returns
the result in a ResultSet object.
2. int executeUpdate():
Executes an SQL stmt. INSERT, UPDATE or
DELETE and returns the count of rows affected.
3. boolean execute():
Executes an SQL stmt. And returns a
e.g.
Consider we have to retrieve the details of
an author by passing author id at runtime.
SELECT * FROM authors WHERE au_id=?
To submit such parameterized query to a
database from an application, we need to create
PreparedStatement object using
perpareStatement() method of the Connection
object.
stmt=con.prepareStatement(“SELECT * FROM
authors WHERE au_id=?”);
The prepareSttaement() method of the
Connection object takes an SQL stmt. as an
The SQL stmt. Can contain ‘?’ symbol as
placeholder that can be replaced by input
parameter at runtime.
Before executing the SQL stmt. Specified in
perpareStatement object we must set the value
for ‘?’ parameter this is done by calling
appropriate setxxx() method where xxx is a
datatype of the parameter.
stmt.setString(1,”1001”);
ResultSet rs=stmt.executeQuery();
The first parameter of setString() method
specifies the index value of the ‘?’ placeholder
and the second parameter is used to set ‘1001’
1. Retrieving rows:
we can use the following code to retrive the
books written by an author from the titles table
using the PreparedStatement object.
public void setInt(int paramIndex, int sets the integer value to the given
value) parameter index.
public void setString(int paramIndex, sets the String value to the given
String value) parameter index.
public void setFloat(int paramIndex, sets the float value to the given
float value) parameter index.
public void setDouble(int paramIndex, sets the double value to the given
double value) parameter index.
.
Common JDBC Components (cont’d..)
• Connection Interface
A Connection is the session between
java
application and database. The
interface is Connection of
aPreparedStatement, factory
and DatabaseMetaData.
The Connection interface Statement,
provide many
methods for transaction management
like commit(),rollback() etc.
.
Commonly used methods of Connection interface
Method Description
.
Commonly used methods of Statement interface
Method Description
public boolean execute(String sql); used to execute queries that may return
multiple results.
.
Prepared Statement
• The PreparedStatement interface is a subinterface of
Statement. It is used to execute parameterized query.
• Example:
String sql="insert into emp values(?,?,?)";
Here, we are passing parameter (?) for the values. Its value will
be set by calling the setter methods of PreparedStatement.
• to get the instance of PreparedStatement the
prepareStatement() method of Connection interface is used
to return the object of PreparedStatement.
• Syntax:
public PreparedStatement prepareStatement(String query)throws
SQLExce
ption{}
.
Methods of PreparedStatement interface
Method Description
public void setInt(int paramIndex, int sets the integer value to the given
value) parameter index.
public void setString(int paramIndex, sets the String value to the given
String value) parameter index.
public void setFloat(int paramIndex, sets the float value to the given
float value) parameter index.
public void setDouble(int paramIndex, sets the double value to the given
double value) parameter index.
.
Common JDBC Components (cont’d..)
• ResultSet Interface
The object of ResultSet maintains a cursor
pointing to a particular row of data. Initially,
cursor points to before the first row.
.
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 row); is used to move the cursor to the specified row number
in the ResultSet object.
public int getInt(int columnIndex); is used to return the data of specified column index of
the current row as int.
public int getInt(String columnName); is used to return the data of specified column name of
the current row as int.
public String getString(int columnIndex); is used to return the data of specified column index of
the current row as String.
public String getString(String is used to return the data of specified column name of
columnName); the current row as String.
.
Advanced Java Programming
Unit-5
Interacting with Database
By
Prof. Mane D.S.
H.O.D. Computer Engineering Department
S.P.M. Polytechnic, Kumathe
Recap
JDBC API classes & Interfaces.
PreparedStatement Interface.
ResultSet Interface.
SQLExceptions
Connecting to Database
• There are 5 steps to connect any java
application with the database in java using
JDBC. They are as follows:
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
.
1.Register the driver class
throws SQLException
public static Connection getConnection(String url,Properties<properties>)
throws SQLException
.
2. Creating connection
p.setProperty(“user”,”new User”);
p.setProperty(“password”,”new password”);
Statement st=con.createStatement();
st.executeUpdate(sql);
while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}
4. Executing queries
• The execute() method of Statement interface is used to
execute queries to the database. This method returns a
boolean value.
Statement st=con.createStatement();
st.execute(sql);
while(rs.next())
System.out.println(rs.getString(1)); }
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.
.
import java.sql.*;
class sample
{
public static void main(String args[])
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
System.out.println("Driver Loaded");
String url="jdbc:odbc:DSN211";
Connection con=DriverManager.getConnection(url);
System.out.println("Connection established");
String sql="Select * from student where Percentage>=70";
.
PreparedStatement ps=con.prepareStatement(sql);
ResultSet rs=ps.executeQuery();
while(rs.next())
{
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getInt(3));
}
ps.close();
con.close();
rs.close();
}
catch(Exception e)
{}
}
}
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/sun","root",“123");
//here sun is database name, root is username and password
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);
}
} //CD:\ePparromt gernat mfoCFomilepuste\rJava\jre1.6.0\lib\ext
AJP- Unit-V 34
Engineering
Prepared Statement Example
import java.sql.*;
class InsertPrepared{
public static void main(String args[]){
try{ Class.forName("oracle.jdbc.driver.OracleDriv
er");
Connection
con=DriverManager.getConnection("jdbc:mysql:/
/localhost:3306/sun","root",“123");
int i=stmt.executeUpdate();
System.out.println(i+" records inserted");
con.close();
}catch(Exception e)
{ System.out.println(e);}
Department of Computer
AJP- Unit-V 35
}Engineering