0% found this document useful (0 votes)
13 views41 pages

AJP Unit 5 Interacting With Database1

The document provides an overview of Java Database Connectivity (JDBC), detailing its purpose as a standard API for connecting Java applications to relational databases. It describes various types of JDBC drivers, their advantages and disadvantages, and outlines the common components of JDBC, such as DriverManager, Connection, Statement, and ResultSet interfaces. Additionally, it includes programming steps for connecting to a database and executing queries using JDBC in Java.

Uploaded by

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

AJP Unit 5 Interacting With Database1

The document provides an overview of Java Database Connectivity (JDBC), detailing its purpose as a standard API for connecting Java applications to relational databases. It describes various types of JDBC drivers, their advantages and disadvantages, and outlines the common components of JDBC, such as DriverManager, Connection, Statement, and ResultSet interfaces. Additionally, it includes programming steps for connecting to a database and executing queries using JDBC in Java.

Uploaded by

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

Unit IV

Interacting with
Database Marks :12
Marks
Created By: Prof.P.M.Takate
JDB

C
 JDBC stands for Java Database Connectivity.
It is a standard Java API for connecting programs written in Java to the
data in relational databases.
 Java database connectivity (JDBC) is the JavaSoft specification of
a standard application programming interface (API) that allows
Java programs to access database management systems.
 The JDBC API consists of a set of interfaces and classes written
in the Java programming language.
 Using these standard interfaces and classes, programmers can write
applications that connect to databases, send queries written in
structured query language (SQL), and process the results.
 JDBC works with Java on a variety of platforms, such as Windows, Mac
OS, and the various versions of UNIX.
ODB
C
 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
Driver
 Java Database Connectivity (JDBC) is an application programming
interface (API), which defines how a client may access any kind of tabular data,
especially relational database.
 It acts as a middle layer interface between java applications and database.
 The JDBC classes are contained in the Java Package java.sql and javax.sql.
 JDBC helps you to write Java applications that manage these three programming
activities:
 Connect to a data source, like a database.
 Send queries and update statements to the database
 Retrieve and process the results received from the database in answer to
your query
Types of JDBC
 Driver
JDBC Driver is a software component that enables java application to interact
with the database.There are 4 types of JDBC drivers:

 Type-1 driver / JDBC-ODBC bridge driver


 Type-2 driver / Native-API driver (partially java driver)
 Type-3 driver / JDBC-Net pure Java / Network-Protocol driver (fully java
driver)
 Type-4 driver / Pure Java Driver / Thin driver / Database-
Protocol driver(fully java driver)
JDBC-ODBC bridge
 The JDBCdriver
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 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.
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.
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.
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.
Thin
 The JDBC type 4 driver, also known as the Direct to Database Pure Java
driver
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.
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 applicationcommunicates 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.
Common JDBC
Components
The JDBC API provides the following interfaces and
classes :

 DriverManager Class
 Driver Interface
 Connection Interface
 Statement Interface
 ResultSet Interface
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().
Commonly used methods of DriverManager
class
Method Description

public static void registerDriver(Driver driver); is used to register the given driver
with DriverManager.

is used to deregister the given


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

public static Connection getConnection(String url); is used to establish the


connection with the specified
url.

public static Connection getConnection(String url, String is used to establish the connection
with the specified url, username
userName, String password); and password.
Common JDBC Components
(cont’d..)
 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. It also abstracts
the details associated with working with Driver objects.
Common JDBC Components
(cont’d..)
 Connection Interface
A Connection is the session between java application and database. The
Connection interface is a factory of Statement, PreparedStatement, and
DatabaseMetaData. The Connection interface provide many methods for
transaction management like commit(),rollback() etc.
Commonly used methods of Connection interface

Method Description

public Statement createStatement(); creates a statement object that can be used


to execute SQL queries.

public void setAutoCommit(boolean status); It is used to set the commit status.


By default it is true.

public void commit(); It saves the changes made since


the previous commit/rollback
permanent.
Drops all changes made since the previous
public void rollback();
commit/rollback.
closes the connection and Releases a JDBC
public void close(); resources immediately.
Common JDBC Components
(cont’d..)
 Statement Interface
The Statement interface provides methods to execute queries with the
database. It provides factory method to get the object of ResultSet.
Commonly used methods of
Statement interface
Method Description

public ResultSet executeQuery(String sql); used to execute SELECT query. It returns


the object of ResultSet.

public int executeUpdate(String sql); used to execute specified query, it may be


create, drop, insert, update, delete etc.

public boolean execute(String sql); used to execute queries that may


return
multiple results.

public int[] executeBatch(); used to execute batch of commands.


Prepared
Statement
 The PreparedStatement interface is a subinterface of Statement. It is used
to execute parameterized query.
 Example:
String sql="insert into emp values(?,?,?)";

( emp_id,emp_name,emp_salary)
( 1,2,3)
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
SQLException{
}
Methods of PreparedStatement
interface Method Description
public void setInt(int paramIndex, int value) sets the integer value to the given
parameter index.
public void setString(int paramIndex, String sets the String value to the given parameter
value) index.
public void setFloat(int paramIndex, float value) sets the float value to the given parameter index.

public void setDouble(int paramIndex, sets the double value to the given
double value) parameter index.
public int executeUpdate() executes the query. It is used for create,
drop, insert, update, delete etc.

public ResultSet executeQuery() executes the select query. It returns an instance


of ResultSet.
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.
is used to move the cursor to the last row in result set
public boolean last();
object.
is used to move the cursor to the specified row number in
public boolean absolute(int row);
the ResultSet object.
is used to return the data of specified column index of the
public int getInt(int columnIndex);
current row as int.
public int getInt(String is used to return the data of specified column name of
columnName); the current row as int.
public String getString(int is used to return the data of specified column index of
columnIndex); 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.
public int getFloat(int is used to return the data of specified column name of
columnIndex); the current row as float.
public int getDouble(int is used to return the data of specified column name of
columnIndex); the current row as double.
JDBC Programming Steps

1) Register the driver


Connect 2) Create a connection to the
database

1) Create a statement
Query 2) Query the database

1) Get a result set


Process Results
2) Assign results to Java
variables

1) Close the result set


Close 2) Close the statement
3) Close the connection
Skeleton Code
Class.forName(DRIVERNAME);
Loading a JDBC driver
Connection con = DriverManager.getConnection(
CONNECTIONURL);

Connecting to a database
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(“SELECT a, b, c FROM member);

While(rs.next()) Executing SQL


{
Int x = rs.getInt(“a”); Processing the result set
String s = rs.getString(“b”);
Float f = rs.getFloat(“c”);
}
Closing the connections
rs.close();
stmt.close();
con.close();
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
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 ClassNotFoundException

 Example to register with JDBC-ODBC Driver

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
2. Creating
connection
The DriverManager.getConnection() method is used
to establish
connection with the database.

 Syntax of getConnection() method

public static Connection getConnection(String url)throws SQLException

public static Connection getConnection(String url,String name,String password)


throws SQLException

 Example establish connection with JDBC Driver


Connection con = DriverManager.getConnection
("jdbc:odbc:DemoDB");
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.

 Syntax of createStatement() method


public Statement createStatement()throws SQLException

 Example to create the statement


object
Statement stmt=con.createStatement();
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.

 Syntax of executeQuery() method


public ResultSet executeQuery(String sql)throws SQLException

 Example to execute query


ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next())
{
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}
 JDBC returns the results of a query in a ResultSet object
 ResultSet object contains all of the rows which satisfied the

conditions in an SQL statement


 A ResultSet object maintains a cursor pointing to its current row of
data
 Use next() to step through the result set row by row
 next() returns TRUE if there are still remaining records
 getString(), getInt(), and getXXX() assign each value to a Java
variable

Internal Pointer ResultSet

Record 1 Record 2 Record 3 Record 4

The internal pointer starts one before the first record


 Example
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(“SELECT ID, name, score FROM
table1”);

While (rs.next()){
int id = rs.getInt(“ID”);
String name = rs.getString(“name”);
float score = rs.getFloat(“score”);
System.out.println(“ID=” + id + “ ” + name + “ ” + score);}

ID name score Output


1 James 90.5 ID=1 James 90.5
2 Smith 45.7
ID=2 Smith 45.7
ID=3 Donald 80.2
3 Donald 80.2

Table1
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.

 Syntax of close() method


public void close()throws SQLException

 Example to close connection


con.close();
import java.sql.*;
class MysqlCon{
public static void main(String args[]){
try {
Class.forName(" sun.jdbc.odbc.JdbcOdbcDriver ");

Connection con=DriverManager.getConnection("jdbc:odbc:Demodb");
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next())
int id=rs.getInt(1);
String name=rs.getString(2);
String Designation=rs.getString(3);
System.out.println(id+" "+name+" "+Designation);
rs.close();
stmt.close();
con.close();
}
catch(Exception e)
{ System.out.println
Prepared Statement Example
import java.sql.*;
class InsertPrepared{
public static void main(String args[]){ try{

Class.forName(" sun.jdbc.odbc.JdbcOdbcDriver ");


Connection con=DriverManager.getConnection("jdbc:odbc:demodb”);
PreparedStatement stmt=con.prepareStatement("insert into Emp values(?,?)");
stmt.setInt(1,101); / / 1 specifies the first parameter in the query
stmt.setString(2,"Ratan"); / / 2 specifies the second parameter in the query
int i=stmt.executeUpdate();
System.out.println(i+" records inserted");
con.close();
}catch(Exception e){ System.out.println(e);}
}
}
Thank You

You might also like