0% found this document useful (0 votes)
38 views24 pages

UNIT V Interacting With DATABASE

Uploaded by

Yør
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)
38 views24 pages

UNIT V Interacting With DATABASE

Uploaded by

Yør
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/ 24

UNIT – V

INTERACTING WITH DATA BASE


Unit Outcomes (UOs): -

5a. Choosing JDBC or ODBC depends on requirements.


5b. Function of JDBC architecture for two tier/Three tier models .
5c.Use of JDBC Drivers for specified environment.
5d. Establish connection with Database.

Total Marks=12
CH-5 INTERACTING WITH DATA BASE

Introduction to JDBC and ODBC

• ODBC stands for Open Database Connectivity. It is basically API i.e. Application Programming Interface.

• Using ODBC driver interface created by Microsoft, an application can access the data present in
Database Management System (DBMS).

• For accessing the data from DBMS, we normally make use of Structured Query Language (SQL)
statements which is popularly known as SQL Queries.

JDBC stands for Java DataBase Connectivity. JDBC is nothing but an API
• It consists of various classes, interfaces, exceptions using which Java application can send SQL statements
to a database. The SQL is a Structured Query Language used for accessing the database.

• JDBC is useful for both application developers and JDBC driver vendors.

• The JDBC specification is prepared by Sun Microsystems. Any third party vendor can design their own JDBC
drivers using this specification. These JDBC drivers are then used by the application developers for getting connected to
the database

JDBC Architecture:

JDBC API supports both two-tier and three-tier processing model.

1) Two Tier Model


2) Three Tier Model
Two Tier Model:
the JDBC driver API is required communicate with database. For this communication, the
JDBC driver API is required.
The Two Tier model is represented by following figure
Three Tier Model

In this architecture, the HTML browser will send the command to Java Application. The Java application will then
communicate with database through JDBC API. The architecture is as shown below –
JDBC Works?
Following is a way by which JDBC works -
First of all Java application establishes connection with the data source.
1)

Then Java application invokes classes and interfaces from JDBC driver for sending queries to the data source.
2)

The JDBC driver connects to corresponding database and retrieves the result.
3)

These results are based on SQL statements which are then returned to Java application.
4)

Java application then uses the retrieved information for further processing
Types of JDBC Drivers

There are four types of JDBC drivers and those are –

1. Type 1 : JDBC-ODBCBridge
2. Type 2 : Native-API/Partly Java Driver
3. Type 3 : All JAVA/ Net Protocol driver for accessing middleware server.
Type 4 : All JAVA/ Native-Protocol Pure driver Let us discuss them in detail –
4.
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.

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 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.
Native-API driver

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.
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:
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.
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:
Better performance than all other drivers.
No software is required at client side or server side.
Disadvantage:
Drivers depend on the Database.
Driver Interfaces
• The JDBC API is a set of classes, interfaces and exceptions used for establishing connection with data
source.
• This JDBC API is defined in the java.sql and javax.sql packages.
• We use following core JDBC classes

• The JDBC API classes are supported by the java package java.sql. Hence we must import java.sql.* in our
program.
Driver Manager Class:
• When Java application needs connection to the database it invokes the
DriverManager class.
• This class then loads JDBC drivers in the memory.
• The DriverManager also attempts to open a connection with the desired
database.
• We have to use following statement for referring the JDBC-ODBC Bridge.

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver") ;
Connection Interface:
• This is an interface which represents connectivity with the data source. The connection is used for
creating the Statement instance.
• To connect, you need to get a Connection instance from JDBC. To do this, you would use the
DriverManager.getConnection() method.

• Following statement can be written

Following statement can be written in your Java program to get connected with database
Thus if we write following two statements in our Java program then we can connect to the database.

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver") ;
con = DriverManager.getConnection("jdbc:odbc:My_database"," ",“);
Write a Java program to simply connect with the database. Sol. :
import java.sql.*;
public class JDBCDemo
{
public static void main(String [ ] args) {
Connection con = null; try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver") ;
con = DriverManager.getConnection("jdbc:odbc:My_database"," "," ");
System.out.println("Connection Successful!");
con.close();
}
catch (ClassNotFoundException e) {
System.err.println("Exception: "+e.getMessage());
}
catch (SQLException e)
{
System.err.println("Exception: "+e.getMessage());} } }

Output:
Connection Successful!
In the above program, essentially we have to
handle two major Exceptions namely :
ClassNotFoundException and SQLException with the help of try-catch block.
Statement Interface:
• A Statement object is used for executing a static SQL statement and obtaining the results produced by it.

• The Statement interface can not accept parameters. Creation of Statement Object

• The statement object can be created using the createStatement() method.

Following is a illustrative Java code


try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver") ;
con = DriverManager.getConnection("jdbc:odbc:My_database"," "," ");
Statement stat=con.createStatement();

}
catch(SQLException ex) {

}
• After creating the statement object one of the following three methods can be invoked.

execute : It Returns true if a ResultSet object can be retrieved; otherwise, it returns false. Use this method to
1.

execute SQL DDL statement. The general syntax is,

bool execute(String SQL)

executeUpdate : It returns the number of rows affected by the execution of the SQL statement. Use this
2.

method to execute SQL statements using the INSERT, UPDATE or DELETE statement. The general syntax is,

int executeUpdate(String SQL)

executeQuery : It returns a ResultSet object. Use this method when you expect to get a result set. Normally this
3.

statement is used with a SELECT statement. The general syntax is,

ResultSet executeQuery(String SQL)

Closing Statement Object


Using a call to close method the Statement object can be closed. For instance
Stat.close();
Types of Statements
There are two types of statements
Prepared statement
1.

Callable statement
2.

Prepared Statement
∙ The java.sql.PreparedStatement interface object represents a precompiled SQL statement.
∙ This interface is used to efficiently execute SQL statements multiple times. That is when we
want to insert a record in a table by putting different values at runtime.
∙ This statement is derived from the Statement class.
∙ The PreparedStatement interface can be created by calling prepareStatement() method.
The prepareStatement() is available in java.sql.Connection interface.
The prepareStatement() method takes SQL statement in java format.
prepareStatement("insert into student values(?,?)").
where each ? represents the column index number in the table. If table student has
rollnumber and name
columns, then 1st ? refers to rollnumber, 2nd ? refers to name.
∙ After that we need to set the value to each ? by using the setter method from
PreparedStatement interface as follows:

setXXX(ColumnIndex,value)
Callable Statement
The callable statement is used when we want to access the database stored procedures. The stored procedure is
basically a block of code which is identified by unique name.

Calling Procedure
When calling the stored procedure, the CallableStatement object is used. For this object three types of parameters are
used.
You can create an instance of a CallableStatement by calling the prepareCall() method on a connection object.
Here is an example :
CallableStatement callableStatement = connection.prepareCall("{call myprocedure(?, ?)}");

ResultSet Interface
• The ResultSet interface is an important interface which is used to access the database table with general width
and unknown length.
• The table rows are retrieved in sequence using ResultSet object. Within a row its column values can be
accessed in any order.
• A ResultSet maintains a cursor pointing to its current row of data. Initially the cursor is positioned before the
first row. The 'next' method moves the cursor to the next row.
• The ResultSet object can be created using executeQuery() method. For example
Statement statement = connection.createStatement();
ResultSet result = statement.executeQuery("select * from my_table");

Navigating Methods in ResultSet Interface


Navigating Methods in ResultSet Interface
Various commonly used navigating methods for ResultSet are as given in the following table.

Sr.
No. Methods Description
public boolean first()
1. throws SQLException Moves the cursor to the first row.

1. public void last() throws SQLException Moves the cursor to the last row.

public boolean previous()


1. throws SQLException Moves the cursor to the previous row. This
method returns false if the
previous row is off the result set.

public boolean next()


• throws SQLException Moves the cursor to the next row.
This method returns false if there
are no more rows in the result set.

5. public int getRow() throws SQLException Returns the row number


that the cursor is pointing to.
Navigating Methods in ResultSet Interface
Various commonly used navigating methods for ResultSet are as given in the following table.

Sr.
No. Methods Description
public boolean first()
1. throws SQLException Moves the cursor to the first row.

1. public void last() throws SQLException Moves the cursor to the last row.

public boolean previous()


1. throws SQLException Moves the cursor to the previous row. This
method returns false if the
previous row is off the result set.

public boolean next()


• throws SQLException Moves the cursor to the next row.
This method returns false if there are
no more rows in the result set.

5. public int getRow() throws SQLException Returns the row number


that the cursor is pointing to.

You might also like