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

ajp chp 5

Uploaded by

rahul13237
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

ajp chp 5

Uploaded by

rahul13237
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 38

Chapter 5

Interacting with Database


Unit outcomes :
1) Choose JDBC or ODBC depending on the given
application requirement.
2) Explain function of the given tier of JDBC
architecture for two tier/ three tier models.
3) Use relevant type of JDBC driver for the specified
environment.
4) Elaborate steps with example to establish
connectivity with the specified database.
What is JDBC?

• JDBC (Java Database Connectivity)


• Java JDBC is a java API to connect and execute
query with the database. JDBC API uses jdbc
drivers to connect with the database.
Why use JDBC
• Before JDBC, ODBC API was the database API
to connect and execute query with the
database.
• But, ODBC API uses ODBC driver which is
written in C language (i.e. platform dependent
and unsecured).
• That is why Java has defined its own API (JDBC
API) that uses JDBC drivers (written in Java
language).
JDBC Architecture
• Two-tier and Three-tier Processing Models
• The JDBC API supports both two-tier and
three-tier processing models for database
access.
Two-tier Architecture for Data Access
Two-tier Architecture for Data Access
• A Java applet or application talks directly to the data
source.
• JDBC drivers are used to communicate with the
particular data source being accessed.
• User's commands are delivered to the database 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.
Three-tier Architecture for Data Access
JDBC Driver Types
• JDBC drivers are divided into four types which
are as follows:

1) Type 1: JDBC-ODBC Bridge driver (Bridge)


2) Type 2: Native-API/partly Java driver (Native)
3) Type 3: All Java/Net-protocol driver
(Middleware)
4)Type 4: All Java/Native-protocol driver (Pure)
Type 1 JDBC Driver
JDBC-ODBC Bridge driver
-> Type 1 driver uses ODBC driver to connect to the database.
-> The JDBC-ODBC Bridge driver converts JDBC method calls into
the ODBC function calls.
-> ODBC is a generic API.
-> It is also called Universal driver because it can be used to
connect to any of the database.
-> The JDBC-ODBC Bridge driver is recommended only for
experimental use or when no other alternative is available.
Three-tier Architecture for Data Access
• 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.
• The middle tier makes it possible to maintain
control over access and the kinds of updates
that can be made to corporate data.
• It also simplifies the deployment of
applications.
• Advantage
The JDBC-ODBC Bridge allows access to almost any
database, since the database's ODBC drivers are
already available.

• Disadvantages
1. Since the Bridge driver is not written fully in Java,
Type 1 drivers are not portable.
2. A performance issue is seen as a JDBC call goes
through the bridge to the ODBC driver, then to the
database, and this applies even in the reverse
process. They are the slowest of all driver types.
3. The client system requires the ODBC Installation
to use the driver.
4. Not good for the Web.
Type 2 JDBC Driver
Native-API/partly Java driver
• Type 2 drivers convert JDBC calls into (native C/C++
API calls) database-specific calls i.e. this driver is
specific to a particular database.
• Example: Oracle will have oracle native API.
• Advantage
Offer better performance than the JDBC-ODBC
Bridge as the layers of communication (tiers) are
less than that of Type 1 and also it uses Native API
which is Database specific.
• Disadvantage
1. Native API must be installed in the Client System
and hence type 2 drivers cannot be used for the
Internet.
2. Like Type 1 drivers, it’s not written in Java
Language which forms a portability issue.
3. If we change the Database we have to change
the native API as it is specific to a database
Type 3 JDBC Driver
Network-Protocol driver/All Java
• Type 3 database requests are passed through the
network to the middle-tier server (application server)
• Middle tier server converts JDBC calls directly or
indirectly into the vendor-specific database protocol.
• Here all the database connectivity drivers are present
in a single server, hence no need of individual client
side installation
• Advantage
1. This driver is server-based, so there is no need for
any vendor database library to be present on client
machines.
2. This driver is fully written in Java and hence Portable.
It is suitable for the web.
3. The net protocol can be designed to make the client
JDBC driver very small and fast to load.
4. This driver is very flexible allows access to multiple
databases using one driver.
5. They are the most efficient amongst all driver types.

• Disadvantage
It requires another server application to install and
maintain. Traversing the recordset may take longer,
since the data comes through the backend server.
Type 4 JDBC Driver
Native-Protocol/Database Protocol/All-Java driver
• The Type 4 uses java networking libraries to
communicate directly with the database server.
• This driver converts JDBC calls directly into the
vendor-specific database protocol, it does not require
any native database library, that is why it is known as
thin driver.
• It is fully written in Java language.
• Advantage
1. This type of drivers are completely written in Java so it
achieves platform independence and eliminate
deployment administration issues. It is most suitable
for the web.
2. Number of translation layers is very less i.e. type 4
JDBC drivers don't have to translate database requests
to ODBC or a native connectivity interface or to pass
the request on to another server, so performance is
also good.
3. No need to install special software on the client or
server.
4. These drivers can be downloaded dynamically.
• Disadvantage
With type 4 drivers, the user needs a different driver for
each database.
Which driver should be used ?
• 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 database at the same time, type 3 is
the preferred driver.
• Type 2 drivers are useful in situations, where
type 3 or type 4 driver is not available.
• Type 1 driver is not considered a deployment
level driver, and is typically used for
development and testing purpose only.
DriverManager class
• It 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.
• It also maintains a list of Driver classes that
have registered themselves by calling the
method DriverManager.registerDriver().
Commonly used methods of
DriverManager class:
1) public static void registerDriver It is used to register the given
(Driver driver): driver with DriverManager.

It is used to deregister the given


2) public static void
driver (drop the driver from the
deregisterDriver (Driver driver):
list) with DriverManager.

3) public static Connection It is used to establish the


getConnection(String url): connection with the specified url.

4) public static Connection It is used to establish the


getConnection(String url,String connection with the specified url,
userName,String password): username and password.
Driver Interface
• Every database driver needs to implement
this interface.
• We can load as many database drivers we
want, but all of them must implement this
interface.
• Each driver will provide a class
implementing the Driver interface.
Connection Interface
• java.sql.Connection interface represents a session
between java application and database.
• All SQL statements are executed and results are returned
within the context of a Connection object.
• The Connection interface provide many methods for
transaction management like commit(), rollback() etc.
• For example :
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("jdbc:odbc:DSN");
Statement Interface
• JDBC API provides 3 different interfaces to
execute the different types of SQL
queries. They are,
1) Statement – Used to execute normal SQL
queries.
2) PreparedStatement – Used to execute
dynamic or parameterized SQL queries.
3) CallableStatement – Used to execute the
stored procedures.
Commonly used methods of
Statement interface:
1) public ResultSet executeQuery(String sql): is
used to execute SELECT query. It returns the
object of ResultSet.
2) public int executeUpdate(String sql): is used
to execute specified query, it may be create,
drop, insert, update, delete etc.
3) public boolean execute(String sql): is used to
execute queries that may return multiple
results.
4) public int[] executeBatch(): is used to execute
batch of commands.
Steps to connect a Java Application
to Database
The following 5 steps are the basic steps involve
in connecting a Java application with Database
using JDBC.
1) Register the Driver
2) Create a Connection
3) Create SQL Statement
4) Execute SQL Statement
5) Closing the connection
1) Register the Driver
• The forName() method of Class class is used to
register the driver class.
• It dynamically loads the driver class into JVM.
• Syntax :
public static void forName(String className)
throws ClassNotFoundException
• Example :
Class.forName("oracle.jdbc.driver.OracleDriver");
Class.forName("Sun.Jdbc.Odbc.JdbcOdbcDriver");
2) Create a Connection
• The getConnection() method of Driver Manager class is
used to create a connection.
• Syntax :
1) public static Connection getConnection(String url)throw
s SQLException
2) public static Connection getConnection(String url,String
name, String password) throws SQLException
• Example :
Connection con=DriverManager.getConnection (
"jdbc:oracle:thin:@localhost:1521:xe","system","password
");
Connection con=new DriverManager.getConnection
(“Jdbc:Odbc:< dsn >", “username",“pswd");
3) Create SQL Statement
• The createStatement() method of Connection
interface is used to create statement.
• The object of statement is responsible to
execute queries with the database.
• Syntax :
public Statement createStatement()throws
SQLException
• Example :
Statement stmt=con.createStatement();
Interfaces and their uses
1) Statement
It is used for general-purpose access to your
database. They are useful when you are using static
SQL statements at runtime. The Statement interface
cannot accept parameters.
2)PreparedStatement
It is used when you plan to use the SQL statements
many times. The PreparedStatement interface
accepts input parameters at runtime.
3)CallableStatement
It is used when you want to access the database
stored procedures. The CallableStatement interface
can also accept runtime input parameters.
4) Execute SQL Statement
• 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 :
public ResultSet executeQuery(String sql)throws
SQLException
Example :
ResultSet rs = stmt.executeQuery
("select * from emp");
while(rs.next())
{
System.out.println(rs.getInt(1)+" "+rs.getString(2)
);
}
Types of execute methods
• Once you've created a Statement object, you can then use it
to execute an SQL statement with one of its three execute
methods.

1) boolean execute (String SQL): Returns a boolean value of


true if a ResultSet object can be retrieved; otherwise, it
returns false. For eg. SQL DDL statements

2) int executeUpdate (String SQL): Returns the number of


rows affected by the execution of the SQL statement.

3) ResultSet executeQuery (String SQL): Returns a ResultSet


object. Use this method when you expect to get a result set, as
you would with a SELECT statement.
5) Closing the connection
• After executing SQL statement you need to close
the connection and release the session.
• The close()method of Connection interface is
used to close the connection.
• Syntax :
public void close() throws SQLException
• Example :
con.close();
import java.sql.*;
class odbcdemo
{
public static void main(String ar[])
{
try
{
String url="jdbc:odbc:mydsn";
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); // Register driver
Connection c=DriverManager.getConnection(url); //Create connection object
Statement st=c.createStatement(); // Create statement
ResultSet rs=st.executeQuery("select * from emptable"); // Execute query
while(rs.next())
{
System.out.println(rs.getString(1));
System.out.println(rs.getString(2));
System.out.println(rs.getString(3));
}
}
catch(Exception e)
{
System.out.println(e);
} } }
import java.io.*;
import java.sql.*;
class product
{
public static void main(String args[]) throws Exception
{
ResultSet r;
int x;
Class. forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection c=DriverManager.getConnection("jdbc:odbc:mydsn");
Statement s=c.createStatement();
String d[][]={{"Remote","TV","Mobile"},
{"101","102","103"},
{"20","10","15"}} ;
s.execute("create table product (prod_name varchar(25), prod_id int,
prod_quantity int)");
s.executeQuery("select * from product");
System.out.println("Table created");
c.close();
c=DriverManager.getConnection("jdbc:odbc:mydsn");
s=c.createStatement();
for(int i=0;i<3;i++)
{
s.executeUpdate("INSERT INTO
product(prod_name,prod_id,prod_quantity)VALUES('"+
d[0][i]+"',"+d[1][i]+","+d[2][i]+")");
}
r=s.executeQuery("select * from product");
while(r.next())
{
x=r.getInt("prod_id");
if (x==103)
System.out.println("\nProduct Name:" + r.getString("prod_name") +
"\t Product ID :" + x + "\t Product Quantity:" +
r.getInt("prod_quantity"));
}
}
}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy