0% found this document useful (0 votes)
6 views38 pages

1 JDBC

This document provides an overview of Java Database Connectivity (JDBC), detailing its objectives, types of JDBC drivers, and essential classes and interfaces. It explains how to execute SQL queries using Statement, PreparedStatement, and CallableStatement, as well as handling BLOB/CLOB data and batch updates. Additionally, it covers transaction management and isolation levels in JDBC.
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)
6 views38 pages

1 JDBC

This document provides an overview of Java Database Connectivity (JDBC), detailing its objectives, types of JDBC drivers, and essential classes and interfaces. It explains how to execute SQL queries using Statement, PreparedStatement, and CallableStatement, as well as handling BLOB/CLOB data and batch updates. Additionally, it covers transaction management and isolation levels in JDBC.
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/ 38

Java Database Connectivity

Chapter 1
Objectives
On completion of this session you will be able to:
 State purpose of JDBC API.
 Describe 4 types of JDBC drivers and their typical
characteristics with usage.
 State functionality of important classes in JDBC
package.
 Use JDBC Statement to execute SQL queries.
 Use JDBC Prepared statement to execute
parameterized queries.
 Use JDBC Callable Statement to invoke stored
procedures.
 Understand how to deal with BLOB/CLOB type of
data
 Understand the batch updates in JDBC
 Understand JDBC transaction
JDBC

Driver Oracle
DB

Driver SQL server


Java JDBC DB
Program API

Driver MS-Access
DB
ResultSet ResultSet ResultSet

Statement PreparedStatement CallableStatement

Application Connection

DriverManager

Oracle Driver JDBC-ODBC


Connection
Driver Sybase Driver

ODBC Driver
Oracle Sybase
Database Database

Access
Database
JDBC(Drivers)
JDBC-ODBC Bridge (Type 1)
Native-API partly Java Driver (Type 2)
Net-Protocol All-Java Driver (Type 3)
Native Protocol All-Java Driver (Type 4)

List of JDBC Drivers


http://industry.java.sun.com/products/jdbc/
drivers
JDBC-ODBC Bridge (Type 1)

Java JDBC ODBC


Application API Layer

JDBC ODBC
ODBC Driver API Database

• Suitable only for prototyping purposes


• Limited to functionality of ODBC driver
• Not suitable for higher volume of transactions
• Inherits all the limitations of ODBC implementation
• Slower in performance
Native-API partly Java Driver (Type 2)

Java JDBC
Vendor API
Application API

JDBC
Driver Database

• Written partly in Java & partly in native code


• Some platform-specific code in addition to Java library
• Uses native ‘C’ language lib calls for Conversion
Net-Protocol All-Java Driver (Type 3)

Java JDBC Driver


JDBC API Native Driver
Client Server

Database
JDBC
Driver

• Uses DB independent protocol to communicate DB-


requests to a server component
• translates requests into a DB-specific protocol
• Since client is independent of the actual DB, deployment
is simpler & more flexible
Native Protocol All-Java Driver (Type 4)
Vendor-Specific
Protocol

JDBC
Java JDBC Driver
API
Client (Pure Java)

Database

• JDBC calls are directly converted to network protocol used


by the DBMS server
• driver usually comes only from DB-vendor
JDBC(Getting Connection)
try {

Class.forName(“sun.jdbc.odbc.JdbcOdbcDrive
r”);
Properties p = new Properties();
p.put(“user”,”dba”);
p.put(“password”,”sql”);
String url = “jdbc:odbc:mytable”;
Connection c =
DriverManager.getConnection(url,p);
}
JDBC URL
Needed by drivers to locate, access and get
other valid information about the databases
jdbc:driver:database-name
jdbc:Oracle:products
jdbc:odbc:mydb; uid = aaa; pwd = secret
jdbc:odbc:Sybase
jdbc:odbc://whitehouse.gov.5000/cats
jdbc:odbc:<DB>
oracle.jdbc.driver.OracleDriver
JDBC(Interfaces)
Driver
Connection
Statement
PreparedStatement
CallableStatement
DatabaseMetadata
ResultSet
ResultSetMetadata
JDBC(Classes)
Date
DriverManager
DriverPropertyInfo
Time
TimeStamp
Types
Driver Interface
Connection connect(String URL, Properties
info):
checks to see if URL is valid
opens a TCP connection to host & port
number specified
returns an instance of Connection object
Boolean acceptsURL(String URL)
Driver Manager class
 Connection getConnection(String URL)
 void registerDriver(Driver driver)
 void deregisterDriver()

Eg : Connection conn = null;


conn =
DriverManager.getConnection(“jdbc:odbc
:mydsn”);
Connection
Represents a session with the DB
connection provided by driver
Developer use this object to execute
queries & action statements & commit or
rollback transactions
JDBC(Connection)
close()
commit()
void setAutoCommit(boolean b)
rollback()
Statement createStatement()
CallableStatement prepareCall(String sql)
PreparedStatement
prepareStatement(String sql)
Statement
Statement

PreparedStatement

CallableStatement

Statement Methods
boolean execute(String sql)
ResultSet executeQuery(String sql)
int executeUpdate(String sql)
JDBC( Simple Query)
String url = “jdbc:odbc:MyDataSource”
Connection con =
DriverManager.getConnection( url);
Statement stmt = con.createStatement();
String sql = “SELECT Last_Name FROM
EMPLOYEES”;
ResultSet rs = stmt.executeQuery(sql);

while(rs.next())
{ System.out.println(rs.getString(“Last
_Name”));
}
JDBC ( executing DML statement)
String url = “jdbc:odbc:MyDataSource”
Connection con =
DriverManager.getConnection( url);
Statement stmt = con.createStatement();
String sql=“insert into employee(empno,
empname,designation,salary)

values(5,'rrr','manager',11000)";
int updateRowCount=stmt.executeUpdate(sql);
JDBC(Parameterised SQL)
String SQL =
“select * from Employees where
First_Name=?”;

PreparedStatement pstat =
con.prepareStatement(sql);

pstat.setString(1, “John”);

ResultSet rs = pstat.executeQuery();

pstat.clearParameters();
JDBC (Stored Procedure)

CREATE OR REPLACE PROCEDURE sp_product


(product_id IN INTEGER balance IN OUT
FLOAT) AS
BEGIN
SELECT bal INTO balance FROM
productDB WHERE id = product_id ;
balance := balance + balance * 0.5 ;
UPDATE productDB
SET bal = balance
WHERE id = product_id ;
END;
Invoking Stored Procedure

CallableStatement cstmt =
con.prepareCall( “{ call sp_product(?,?)}
”);
cstmt.setInt(1,id);
cstmt.setFloat(2, 5888.86);
cstmt.registerOutParameter(2,Types.FLOAT);

cstmt.execute();

System.out.println(cstmt.getFloat(2));
Creating JDBC 2.0
Resultset
Statement stmt =
conn.createStatement(type,concurrency);

TYPE_FORWARD_ONLY
TYPE_SCROLL_INSENSITIVE
TYPE_SCROLL_SENSITIVE
CONCUR_READ_ONLY
CONCUR_UPDATEABLE
Scrollable & Updatable
ResultSet
Cursor Movement (Scrolling) Methods
first()
last()
next()
previous()
beforeFirst()
afterLast()
absolute( int )
relative( int )
Scrollable & Updatable ResultSet

 Update a row

Statement stmt =
con.createStatement(ResultSet.TYPE_SCROLL_
SENSITIVE, ResultSet.CONCUR_UPDATABLE);

ResultSet rs = stmt.executeQuery(“Select ….”);

rs.first();
rs.updateInt(2, 75858 );
rs.updateRow();
Scrollable & Updatable
ResultSet
 Insert and delete a row
ResultSet rs = stmt.executeQuery(“Select
….”);

rs.moveToInsertRow();
rs.updateString(1, “fkjafla” );
rs.updateInt(2, 7686);
rs.insertRow();

rs.last();
rs.deleteRow();
ResultSetMetadata Interface
ResultSetMetaData represents structure of
any ResultSet Object
It can be used to create generic code which
can be used with any ResultSet Object
DatabaseMetadata Interface
DatabaseMetaData represents
configuration, system structure, capabilities
of a database.
It can be used to create generic application
which deals with multiple databases.
Utilities that can be developed around it:
retrieve all table names
retrieve capabilities of database like SQL.
keyword supported, privileges etc.
retrieve indexes created.
JDBC(BLOB)
Following code snippet will insert an image
in to a database.

FileInputStream fin=new
FileInputStream(f);
PreparedStatement
pstat=con.prepareStatement("Insert into
Emp values(?,?,?,?)");
pstat.setString(1,name);
pstat.setInt(2,id);
pstat.setDouble(3,salary);
pstat.setBinaryStream(4,fin,
(int)length);
pstat.executeUpdate();
JDBC(BLOB)
Following code snippet will retrieve an
image from a database.
Statement
stmt=con.createStatement(“select * from
Emp”);
ResultSet rs=stmt.executeQuery( );
while(rs.next( )){
System.out.println(rs.getString(1));
System.out.println(rs.getInt(2));
System.out.println(rs.getDouble(3));
InputStream
in=rs.getBinaryStream(4);
……………..
}
JDBC(Batch Updates)
Statement stmt=con.createStatement();
stmt.addBatch(sql1);
stmt.addBatch(sql2);
stmt.addBatch(sql3);
stmt.executeBatch();
JDBC (Transactions)

TRANSACTION_NONE

Indicates that transactions are not


supported.
JDBC (Transactions)
TRANSACTION_READ_UNCOMMITTED

Dirty reads, non-repeatable reads and


phantom reads can occur. This level allows
a row changed by one transaction to be
read by another transaction before any
changes in that row have been committed
(a "dirty read"). If any of the changes are
rolled back, the second transaction will
have retrieved an invalid row.
JDBC (Transactions)
TRANSACTION_READ_COMMITTED

Dirty reads are prevented; non-repeatable


reads and phantom reads can occur. This
level only prohibits a transaction from
reading a row with uncommitted changes
in it.
JDBC (Transactions)
TRANSACTION_REPEATABLE_READ
Dirty reads and non-repeatable reads are
prevented; phantom reads can occur. This
level prohibits a transaction from reading a
row with uncommitted changes in it, and it
also prohibits the situation where one
transaction reads a row, a second
transaction alters the row, and the first
transaction rereads the row, getting
different values the second time (a "non-
repeatable read").
JDBC (Transactions)
TRANSACTION_SERIALIZABLE
Dirty reads, non-repeatable reads and
phantom reads are prevented. This level
includes the prohibitions in
TRANSACTION_REPEATABLE_READ and
further prohibits the situation where one
transaction reads all rows that satisfy a
WHERE condition, a second transaction
inserts a row that satisfies that WHERE
condition, and the first transaction rereads
for the same condition, retrieving the
additional "phantom" row in the second
read.
Quick Recap
JDBC is used to connect with databases.
Connectivity to databases is obtained
through 4 types of Drivers.
Connection, Statement, ResultSet
interfaces are used to manipulate data.
Stored Procedures can be executed using
CallableStatement.
ResultSet can be scrollable as well as
updatable.
JDBC provides supports for transactions
through isolation levels.

You might also like