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

CHAPTER 05 JDBC-ODBC (1)final copy

AJP notes on CHAPTER 05 JDBC-ODBC

Uploaded by

aryankaldate6
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)
4 views

CHAPTER 05 JDBC-ODBC (1)final copy

AJP notes on CHAPTER 05 JDBC-ODBC

Uploaded by

aryankaldate6
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/ 42

Chapter No-05

Jdbc and Odbc


Architecture

Prepared By,
Suwarna Thakre
Two tier architecture:

⚫Two tier architecture is similar to a basic client-


server model. The application at the client end directly
communicates with the database at the server side. API’s
like ODBC,JDBC are used for this interaction. The server
side is responsible for providing query processing and
transaction management functionalities
Three Tier architecture:

⚫In this type, there is another layer between the client and the server.
The client does not directly communicate with the server. Instead, it
interacts with an application server which further communicates with
the database system and then the query processing and transaction
management takes place. This intermediate layer acts as a medium
for exchange of partially processed data between server and client.
This type of architecture is used in case of large web applications.
Difference between two tier and three tier
It is a Client-Server Architecture. It is a Web-based application.

Two-tier architecture consists of two layers : Client Three-tier architecture consists of three layers : Client
Tier and Database (Data Tier). Layer, Business Layer and Data Layer.

It is easy to build and maintain. It is complex to build and maintain.

Two-tier architecture runs slower. Three-tier architecture runs faster.

It is less secured as client can communicate with It is secured as client is not allowed to communicate
database directly. with database directly.

It results in performance loss whenever the system is


It results in performance loss whenever the users
run on Internet but gives more performance than two-
increase rapidly.
tier architecture.

Example – Designing registration form which contains


Example – Contact Management System created using
text box, label, button or a large website on the
MS-Access or Railway Reservation System, etc.
Internet, etc.
JDBC Architecture
⚫Java application cannot directly communicate with
database to submit and retrieve the result of queries.
This is because a database can interpret only SQL
Statements and not a java language statements For this
reason we need a mechanism to translate java statement
into SQL Statements. JDBC Architecture provides the
mechanism for this kind of translation.
JDBC Architecture
The JDBC architecture can be classified into
two layers.

⚫JDBC Application layer: Signifies a java application


that uses the JDBC API to interact with the JDBC
DRIVERS. A JDBC driver is a software that a java
application uses to access a database . The JDBC Driver
manager of JDBC API connects the java application to
the driver .
Continue…
⚫JDBC Driver Layer: It acts as an interface between a java
application and a database. This layer contains a driver ,such as a
SQL Server driver or an oracle driver ,which enables connectivity
to database. A driver sends the request of java application to the
database. After processing the request, the database sends the
response back to the driver. The driver translates and sends the
response to the JDBC API, The JDBC API forward it to the java
application ,the following shows the JDBC Architecture:
JDBC DRIVERS

⚫When we develop JDBC applications, we need to use


JDBC drivers to convert queries into form that a particular
database can interpret. The JDBC Driver also retrieves the
result of SQL statements and convert the result into
equivalent JDBC API Class object that the java application
uses As the JDBC only takes care of interactions with the
database ,any change made to database does not affect the
application.
JDBC Drivers

JDBC supports four types of drivers,they are


⚫JDBC-ODBC Bridge driver
⚫Native API Partly-Java driver
⚫JDBC-Net-Pure-Java driver
⚫Native protocol Pure java driver
JDBC-ODBC Bridge Driver
⚫The JDBC-ODBC Bridge driver is called type-1 driver. The
JDBC-ODBC Bridge driver converts JDBC call to Open
Database Connectivity(ODBC) calls.
⚫ODBC is an open standard API to communicate with
databases.
⚫The JDBC-ODBC Bridge driver enables a java application to
use any database that supports ODBC Driver.
JDBC-ODBC Bridge Driver
⚫A java application cannot interact directly with the ODBC driver for this
reason, the application uses the JDBC-ODBC Bridge driver that works
as an interface between the application and the ODBC driver.
⚫To use JDBC-ODBC Bridge driver we need to have the ODBC driver
installed on the client computer.
⚫The JDBC-ODBC Bridge driver is usually used in stand-alone
applications.The following figure shows the working of the JDBC-ODBC
Bridge driver
JDBC-ODBC Bridge Driver
JDBC API

⚫We need to use database drivers and JDBC API while


developing a java application to retrieve or store data in
database. The JDBC API Classes and interfaces are available
in java.sql package or javax.sql Package The classes and
interfaces perform a number of tasks, such as establish and
close a connection with database,send a request to database
,retrieve the data from database and update data in database
Commonly used classes and interfaces in the
JDBC API are:
⚫DriverManager Class : Load driver for database

⚫ Driver interface: Represent database driver. All JDBC driver classes must
implement the Driver interface

⚫Connection interface:- It enable to established connection between a java


application and a database.

⚫Statement interface:- It execute SQL Statements

⚫ResultSet interface: Represents the information retrieved from database

⚫SQLException class: Provide information about the exceptions that occur while
interacting with databases
Loading Driver

⚫The first step to develop a JDBC application is to load and


register the required driver using the driver manager ,we can
load and register a driver.

⚫Using the forName() method

⚫Using the registerDriver() method


Using forName() method

⚫It is available in java.lang.Class class The forName() method load


JDBC Driver and register the driver with the driver manager,the
syntax to load a JDBC driver to access a database is:

Class.forName(“<driver-name”);

⚫We can load JDBC-ODBC Bridge driver using the following


method call

Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
Connecting to Database

⚫Create a object of Connection interface to establish a connection


of the java application with a database. We can create multiple
Connection objects in a java application to access and retrieve data
from multiple databases.
⚫The Driver manager class provides the getConnection() method to
create a Connection object .The getConnection () method is an
overloaded method that has the following forms:
getConnection() Method
⚫Connection getConnection(String < url>)
Accept the JDBC url of the database,which we need to
access as a parameter
Example:
String url=”jdbc:odbc:mydatasource”;
Connection con=DriverManager.getConnection(url);
getConnection() Method
⚫The syntax for a JDBC URL that is passed as a parameter to the getConnection() method
is:

<protocol>:<subprotocol>:<subname>

⚫Protocol name: Indicates the name of the protocol that is used to access a database In
JDBC ,the name of access protocol is always jdbc.

⚫Subprotocol name:-Indicates the mechanism to retrieve data from database for eg.if we
use JDBC-ODBC Bridge driver to access a database,then the name of subpritocol id odbc.

⚫Subname: Indicates Data Source Name(DSN) that contain the database information,such
as name of database,location of database,server,username and password to access a
database server.
getConnection() Method
⚫Connection getConnection(String
<url>,String<username>,String <password>)

⚫Accept the JDBC url of a database.It also accepts the user name
and password of the authorized database user.
Creating and Executing JDBC Statement
We need to create a Statement object to send requests to and retrieve
results from a database.The Connection object provides the
createStatement() method to create a Statement object.we can use following
syntax to create a Statement object.

Example:

String url=”jdbc:odbc:mydatasource”;

Connection con=DriverManager.getConnection(url);

Statement st=con.createStatement();
Continue….
⚫We can use SQL Statement to send requests to database.
The SQL statement that do not contain run time parameters
are called static SQL statements we can send SQL
statement to a database using the Statement object, The
statement interface contains following methods to send
static SQL statements to a database.
Statement interface method
⚫ResultSet executeQuery(String str):Execute SQL statement and
return a single object of the type ResultSet. This object provides method to
access the data from resultSet. The executeQuery() method should be use
when we need to retrieve datafrom database table using SELECT statement.

The syntax to use executeQuery() method is

Statement st=con.createStatement();

ResultSet rs=st.executeQuery(<sql statement>); In the syntax, st is


a reference to the object of the Statement interface. The executeQuery()
method executes an SQL Statement and the result retrieved from a database
is stored in rs,the resultSet object.
Statement interface method
⚫int executeUpdate(String str):-- Execute SQL statement and returns number of data
rows that are affected after processing the SQL Statement when we need to modify data in a
database table using Data Manipulation Language(DML) Statements,INSERT,DELETE and
UPDATE,we can use executeUpdate() method.

The syntax to use executeUpdate() method

Statement st=con.createStatement();

int count=st.executeUpdate(<sql statement>);

In the syntax,the executeUpdate() executes an SQL statement and number of rows affected in
database is stored in count
Statement interface method
⚫boolean execute(String str) :-Executes an SQL statement and returns
a Boolean value .we can use this method when SQL statement passed as
parameter is not known or when the statement being executed return a
result set 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
The syntax to use executeUpdate() method
Statement st=con.createStatement();
st.execute(<sql statement>);
write a program to create a
table using statement interface
import java.sql.*; String s="create table stud_record (age
class create12 int, add char)";
{ st.executeUpdate(s);
public static void main(String ar[]) System.out.println("table created");
{ con.close();
try st.close();
{ }
Class.forName("sun.jdbc.odbc.Jdbc catch(Exception e)
OdbcDriver"); {}
System.out.println("driver loaded"); }}
String url="jdbc:odbc:even";
Connection con=
DriverManager.getConnection(url);
System.out.println("connection
created");
Statement
st=con.createStatement();
Wap to insert data into table
using statement interface
import java.sql.*; Statement st=con.createStatement();
class data_create String str="insert into IF4G
{ values(112,'suw')";
public static void main(String ar[]) st.executeUpdate(str);
{ System.out.println("data inserted"+i1);
try st.close();
{ con.close();
Class.forName("sun.jdbc.odbc.JdbcOdbcDri }
ver"); catch(Exception e)
System.out.println("driver loaded"); {
String url="jdbc:odbc:god"; }
Connection }
con=DriverManager.getConnection(url);
System.out.println("connection created");
Retrieve data from table

import java.sql.*; ResultSet rs=ps.executeQuery();


class ps_select while(rs.next())
{ {
public static void main(String ar[]) System.out.println("roll-->"+rs.getInt(1));
{ System.out.println("namel-->"+rs.getString(2));
try }
{ con.close();
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); ps.close();
System.out.println("driver loaded"); }
String url="jdbc:odbc:insert1"; catch(Exception e)
Connection {}}}
con=DriverManager.getConnection(url);
System.out.println("connection created");
String str="select * from if6g";
PreparedStatement
ps=con.prepareStatement(str);
WAP to delete row from table

import java.sql.*; String str="delete from if6g where


class delete roll=12";
{ System.out.println("data deleted");
public static void main(String ar[]) st.executeUpdate(str);
{ con.close();
try st.close();
{ }
Class.forName("sun.jdbc.odbc.JdbcOdbcDri catch(Exception e)
ver"); {
System.out.println("driver loaded"); }
String url="jdbc:odbc:delete"; }
Connection }
con=DriverManager.getConnection(url);
System.out.println("connection created");
Statement st=con.createStatement();
Methods of ResultSet Interface
Methods Description
boolean first() Shift the control of result set cursor to the first row of the result set

boolean isFirst() Determine whether the result set cursor points to the first row of the result
set

boolean beforeFirst() Shift the control of result set cursor before the first row of the result set

boolean isBeforeFirst() Determine whether the result set cursor points before the first row of the
result set

boolean last() Shift the control of result set cursor to the last row of the result set

boolean isLast() Determine whether the result set cursor points to the last row of the result
set

boolean afterLast() Shift the control of result set cursor after the last row of the result set

boolean isAfterLast() Determine whether the result set cursor points to the first row of the result
set

boolean previous() Shift the control of result set cursor to the previous row of the result set

boolean absolute(int i) Shift the control of result set cursor to the row number that we specify as a
parameter.
PreparedStatement interface

⚫The prepared statement interface is derived from the


Statement interface and is available in java.sql package. The
preparedStatement is used to pass the run time parameters
to SQL statement to query and modify the data in table
⚫The prepared statement objects are compiled and prepared
only once by JDBC .
Methods of prepared statement interface

⚫ResultSet executeQuery():-Execute a select statement and


returns the result in a ResultSet object

⚫Int executeUpdate():-- execute an SQL Statement,insert,update


or delete and returns the count of the rows affected

⚫boolean execute():--Executes an SQL Statement and return


Boolean value
Example of PreparedStatement interface

Consider we have to retrieve the details of an author by passing author id at

run time

The SQL statement to write a parameterized query is:

Select * from authors where au_id=?

To submit such parameterized query to a database from an application,we

need to create a PreparedStatement object using the preparedStatement()

method of Connection object . We can use the following method call to

prepare an SQL Statement that accept values at run time


Continue….
PreparedStatement st=con.prepareStatement(“select * from authors where
au_id=?”);

prepareStatement() method of the Connection object takes an SQL statement as a


parameter.The SQL statement can contain ‘?’ symbol as place holder that can be
replaced by input parameter at run time

Before executing the SQL statement specified in the preparedStatement object


,set the value of each ‘?’ parameter.this is done by calling an appropriate setXXX()
method ,where xxx is the data type of parameter
setString() method

Example:

PreparedStatement st=con.prepareStatement(url);
St.setString(1,”1001”);
ResultSet rs=st.executeQuery()

First parameter of the setString() method specifies the index


value of ‘?’ placeholder and second parameter is used to set
‘1001’ as the value of ‘?’ holder
Methods of PreparedStatement
interface
⚫The preparedStatement interface provides various
methods to set the value of placeholder for specific data
type
Methods of PreparedStatement interface
METHOD DESCRIPTION

Void setByte(int index,byte value) Set the java byte type value for the parameter
Corresponding to index passed as a parameter
Void setBytes(int index,byte[] value) Set the java byte type array for the parameter
Corresponding to index passed as a parameter
Void setBoolean(int index, boolean val) Set the java Boolean type value for the parameter
Corresponding to index passed as a parameter

Void setDouble(int index, double val) Set the java double type value for the parameter
Corresponding to index passed as a parameter

Void setInt(int index, int val) Set the java int type value for the parameter
Corresponding to index passed as a parameter
Void setLong(int index, long val) Set the java long type value for the parameter
Corresponding to index passed as a parameter
Void setFloat(int index, float val) Set the java float type value for the parameter
Corresponding to index passed as a parameter
Void setShort(int index, short val) Set the java short type value for the parameter
Corresponding to index passed as a parameter
Void setString(int index, String val) Set the java String type value for the parameter
Select Data From Table Using ps
import java.sql.*;
class select1_ps ResultSet rs=st.executeQuery();
while(rs.next())
{public static void main(String ar[])
{
{try System.out.println("bookid"+rs.getInt(1));
{Class.forName("sun.jdbc.odbc.JdbcOdbcDri System.out.println("bookname”+rs.getString
ver"); (2));
System.out.println("driver loaded"); }
st.close();
String url="jdbc:odbc:god1";
con.close();
Connection }
con=DriverManager.getConnection(url); catch(Exception e)
bookid bookname

System.out.println("connection created"); {
11 PIC
String str="select * from author "; }}} 12 JAVA

PreparedStatement 13 PHP

st=con.prepareStatement(str);
Update table using prepared
statement interface
import java.sql.*;
String str="update author set
class update123 name=‘JAVA' where bookid=?";
{ PreparedStatement
public static void main(String ar[]) ps=con.prepareStatement(str);
{ ps.setInt(1,12);
try ps.executeUpdate();
{
Class.forName("sun.jdbc.odbc.JdbcO con.close();
dbcDriver"); st.close();
System.out.println("driver loaded"); }
String url="jdbc:odbc:dsn"; catch(Exception e) bookid bookname

Connection {
con=DriverManager.getConnection(
url); }}} 11 PIC

12 JAVA
System.out.println("connection
created"); 13 PHP
Delete row from table using prepared statement
interface
PreparedStatement
import java.sql.*; st=con.prepareStatement(str);
class update1_ps
{ int bookid=111;
public static void main(String ar[]) st.setInt(1,bookid);
{ st.executeUpdate();
try System.out.println(“row deleted");
{ st.close();
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); con.close();
System.out.println("driver loaded");
String url="jdbc:odbc:god1"; }
Connection catch(Exception e)
con=DriverManager.getConnection(url); {
System.out.println("connection created"); }}}
String str=“delete from author where bookid=?”
Insert data into table using ps

int bookid=111;
import java.sql.*; st.setInt(1,bookid);
class ps_insert st.setString(2,"sss");
{ st.executeUpdate();
public static void main(String ar[]) System.out.println("data inserted");
{try st.close();
{Class.forName("sun.jdbc.odbc.JdbcOdbcDriver") con.close();
; }catch(Exception e)
System.out.println("driver loaded"); {}}}
String url="jdbc:odbc:god1";
Connection
con=DriverManager.getConnection(url);
System.out.println("connection created");
String str="insert into studentty values (?,?)";
PreparedStatement
st=con.prepareStatement(str);

You might also like