0% found this document useful (0 votes)
3 views64 pages

JDBC

The document provides an overview of database systems, focusing on relational databases and the use of SQL for querying. It discusses the differences between ODBC and JDBC, highlighting the advantages of JDBC, including its Java-based architecture and support for multiple database drivers. Additionally, it covers JDBC architecture, connection management, transaction handling, and the use of ResultSets and metadata in database operations.

Uploaded by

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

JDBC

The document provides an overview of database systems, focusing on relational databases and the use of SQL for querying. It discusses the differences between ODBC and JDBC, highlighting the advantages of JDBC, including its Java-based architecture and support for multiple database drivers. Additionally, it covers JDBC architecture, connection management, transaction handling, and the use of ResultSets and metadata in database operations.

Uploaded by

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

Introduction

• Most popular form of database system is the


relational database system.
• Examples: MS Access, Sybase, Oracle, MS Sequel
Server.
• Structured Query Language (SQL) is used among
relational databases to construct queries.
Simple Database Application
A
P DBMS DB
P
L Ex: Access
I Oracle
C Sybase
A
T
I
O
N
Multi-Databases
A
P DBMS 1
P
L
I
C DBMS 2
A
T
I
O DBMS 3
N
Standard Access to DB
A
D DBMS
P DBMS 1 DB
P R Driver 1
L I
I V
E DBMS DBMS 2
C DB
R Driver 2
A
T
I M DBMS
O G Driver 3 DBMS 3 DB
N R
ODBC
• ODBC offers a set of specifications to
the server side database engines.Any
client can Connect to the server, if the
server follows these specifications
properly.
ODBC Interface
• ODBC (Open Database Connectivity) is a Microsoft
standard from the mid 1990’s.
• It is a system independent interface to database
environment that requires an ODBC driver to be
provided for each database system from which you
want to manipulate data.
• The database driver bridges the differences between
your underlying system calls and the ODBC interface
functionality.
ODBC Architecture
Client

ODBC
API

ODBC ODBC ODBC


DRIVER DRIVER DRIVER

Database Database Database


Server Server Server
Why JDBC
Drawbacks of ODBC

•ODBC API was completely written in C language.


Calls to native C code have a number of drawbacks
in the security.
•ODBC drivers must be installed on Client’s
machine.
Advantages of JDBC

1 The JDBC API was completely written in


Java language.
2 A pure java solution allows JDBC driver to
be automatically downloaded and installed
along with Applets.
What is JDBC?

• JDBC is an interface which allows Java cod


e to execute SQL statements inside relationa
l databases
JDBC Architecture
JDBC Application

JDBC Driver Manager

JDBC Drivers

Application JDBC Driver


Overall Architecture
JDBC in Use

Java JDBC
program driver
connectivity for Oracle
data processing
utilities driver
for Sybase

jdbc-odbc odbc
bridge driver
• Java code calls JDBC library
• JDBC loads a driver
• Driver talks to a particular database
• Can have more than one driver -> more than one
database
Java Application

Native API
JDBC-ODBC Partly java
Bridge Driver Driver

JDBC-Net-
ODBC All Java Driver

network

Odbc/OCI

DB DB DB
DB
Four Kinds of JDBC Drivers

• 1. JDBC-ODBC Bridge
– translate Java to the ODBC API

• 2. Native API
– translate Java to the database’s own API
Four Kinds of JDBC Drivers
• 3. Net Protocol
– use Java to access the database via networking
middleware (usually TCP/IP)
– required for networked applications
• 4. Native Protocol
– use Java to access the database more directly us
ing its low level protocols
Type I Driver (The JDBC-ODBC
Bridge )
• The JDBC-ODBC Bridge allows java code to use
the C/C++ interface of ODBC
• Use bridging technology
• Requires installation/configuration on client
machines
• Not good for Web
• e.g. ODBC Bridge
• The layers of Transaction (JavaCSQL) can
slow down execution
Type II Driver
• Native API drivers
• Requires installation/configuration on client
machines
• Not suitable for applets
• Faster than ODBC
• Least flexible
• e.g. Oracle Driver
Type III Driver
• Leads to three tier architecture
• Calls middleware server, usually on database host
• Very flexible -- allows access to multiple databases
using one driver
• But it’s another server application to install and
maintain
• Suitable for intranets & internet
• e.g. IDS Server
Type IV Driver
• 100% Pure Java
• Use Java networking libraries to talk directly to
database engines
• No special s/w required on client side
• More secured,faster access
• Only disadvantage: need to download a new driver
for each database engine
• e.g. Oracle, mySQL
JDBC APIs
• JDBC is implemented via classes in the java.sql package
Interfaces Classes
CallableStatement DriverManager
Connection Date
DatabaseMetaData Time
Driver Types
PreparedStatement
ResultSet
ResultSetMetaData
Statement
Driver Manager
• DriverManager tries all the drivers
• Uses the first one that works
• When a driver class is first loaded, it registers
itself with the DriverManager
• Therefore, to register a driver, just load it!
Driver Manager
• DriverManager
– Loads, chooses drivers
• Driver
– connects to actual database
• Connection
– a series of SQL statements to and from the DB
• Statement
– a single SQL statement
• ResultSet
– the records returned from a Statement
–Loads, chooses drivers
DriverManager

Driver
–connects to actual database a series of SQL statements to
and from the DB
Connection

Statement
a single SQL statement

ResultSet

the records returned from a Statement


creates creates creates
DriveManager Connection Statement ResultSet

SQL
data
Driver
make link
to driver

SQL data
Basic Steps to access DB using
JDBC
•Import the java.sql package
•Load and register the driver
•Establish the connection to the database
•Create a statement
•Execute the statement
•Retrieve the results
•Close the statement and connection
JDBC URLs

jdbc:subprotocol:source
• each driver has its own subprotocol
• each subprotocol has its own syntax for the
source
jdbc:odbc:DataSource
– e.g. jdbc:odbc:cdac
jdbc:mysql://host[:port]/database
Driver Manager

Connection getConnection
(String url, String user,
String password)
• Connects to given JDBC URL with given
user name and password
• Throws java.sql.SQLException
• returns a Connection object
Connection
• A Connection represents a session with a specific
database.
• Within the context of a Connection, SQL statements are
executed and results are returned.
• Can have multiple connections to a database
• Also provides “metadata” -- information about the
database, tables, and fields
• Also methods to deal with transactions
Obtaining a Connection
String url = "jdbc:odbc:cdac";
try {
Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con =
DriverManager.getConnection(url,userid,password);
}
catch (ClassNotFoundException e)
{ e.printStackTrace(); }
catch (SQLException e)
{ e.printStackTrace(); }
Connection Methods
Statement createStatement()
– returns a new Statement object
PreparedStatement prepareStatement(String
sql)
– returns a new PreparedStatement object
CallableStatement prepareCall(String sql)
– returns a new CallableStatement object
Statement
The Statement object provides a ‘workspace’ where
SQL queries can be created and results collected.
Methods
ResultSet executeQuery(String)
– Execute a SQL statement that returns a single ResultSet.
int executeUpdate(String)
– Execute a SQL INSERT, UPDATE or DELETE statement.
Returns the number of rows changed.
boolean execute(String)
– Execute a SQL statement that may return multiple results.
ResultSet
• A ResultSet provides access to a table of data
generated by executing a Statement.
• Only one ResultSet per Statement can be open at
once.
• The table rows are retrieved in sequence.
• A ResultSet maintains a cursor pointing prior to its
current row of data.
• The 'next' method moves the cursor to the next
row.
– you can’t rewind
ResultSet Methods
• boolean next()
– activates the next row
– the first call to next() activates the first row
– returns false if there are no more rows
• void close()
– disposes of the ResultSet
ResultSet Methods
• String getString(int columnIndex)
• boolean getBoolean(int columnIndex)
• byte getByte(int columnIndex)
• short getShort(int columnIndex)
• int getInt(int columnIndex)
• long getLong(int columnIndex)
• float getFloat(int columnIndex)
• double getDouble(int columnIndex)
• Date getDate(int columnIndex)
• Time getTime(int columnIndex)
• Timestamp getTimestamp(int columnIndex)
ResultSet Methods
• String getString(String columnName)
• boolean getBoolean(String columnName)
• byte getByte(String columnName)
• short getShort(String columnName)
• int getInt(String columnName)
• long getLong(String columnName)
• float getFloat(String columnName)
• double getDouble(String columnName)
• Date getDate(String columnName)
• Time getTime(String columnName)
• Timestamp getTimestamp(String columnName)
Transactions
• A logical unit of work
• Either a single or set of SQL statements either all
execute successfully or all of them fail compulsory.
Properties
• Atomic - All the sts treated as a single unit
• Consistent – user should see the same data until the
transaction completes
• Isolation – each transaction should be treated
separately
• Durability – changes can be made permanent
Transaction Management

• Transactions are not explicitly opened and


closed
• Instead, the connection has a state called
AutoCommit mode
• if AutoCommit is true, then every statement
is automatically committed
• default case: true
setAutoCommit
Connection.setAutoCommit(boolean)
• if AutoCommit is false, then every statement
is added to an ongoing transaction
• you must explicitly commit or rollback the
transaction using Connection.commit() and
Connection.rollback()
Database Time
• Java defines three classes to help
• java.sql.Date
– year, month, day
• java.sql.Time
– hours, minutes, seconds
• java.sql.Timestamp
– year, month, day, hours, minutes, seconds, nanoseconds
– usually use this one
Optimized Statements

• Prepared Statements
– allows driver to optimize (compile) queries
– created with Connection.prepareStatement()
– Execution time is much faster
– Improves the response time
Stored Procedures
–Written in DB-specific language
–Stored inside database
–No need to recompile
–Can be used by different people
–Improves response time
Callable Statement

–Used for calling the stored procedures


–Accessed with Connection.prepareCall()
JDBC Class Diagram
Scrollable / Updatable ResultSets
JDBC Cursor Types
• Two parameters
– ResultSet type
– ResultSet concurrency
ResultSet type
• TYPE_FORWARD_ONLY
-cursor may move only forward.
• TYPE_SCROLL_INSENSITIVE
-scrollable but generally not sensitive to
changes made by others.
• TYPE_SCROLL_SENSITIVE
-scrollable and generally sensitive to changes
made by others.
ResultSet concurrency

• CONCUR_READ_ONLY
-may NOT be updated.
• CONCUR_UPDATABLE
-may be updated.
ResultSet Type
• Two dimensions
– forward-only vs scrollable
– insensitive vs sensitive

• possibilities
– forward-only
– scrollable, sensitive
– scrollable, insensitive
ResultSet Concurrency
• Updatable
– Can the ResultSet be used to modify the database?
• Two possibilities
– read-only
– updatable
JDBC Cursors
Database ResultSet

can generate
next row of only current row Application Forward-Only
results accessible

Database ResultSet

can generate
any row of
all rows
accessible Application Scrollable
results

Database ResultSet

can generate all rows


and modify any accessible & Application Updatable
row of results modifiable
Using ResultSet Types
• Statement
– RS types are assigned to a Statement
– ResultSet created by that Statement will have the
given properties

Statement stmt = conn.createStatement(


ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stmt.executeQuery (querySQL);
Scrollable ResultSet
• Can move both directions in results
• Can jump around
• Methods
– previous ()
– absolute ()
– relative ()
– last ()
– first ()
Sensitive vs Insensitive
INSERT INTO
SELECT * FROM
Reservations
Reservations
VALUES (...)

Reservations table

• If insert happens first, query will return new row


• If select happens first?
– insensitive cursor will not return new row
– sensitive cursor will/should return new row
Updatable ResultSet
• Use results of SELECT query
– perform INSERT, DELETE, and UPDATE
• Useful for interactive DB editing
Update Process
1. Connect to database
2. Create an updatable statement
3. Call executeQuery to get ResultSet
4. Navigate to a row
5. Call update methods to modify contents
6. Call updateRow () to commit changes
Update Methods
• Examples
– rs.updateString (1, “Jack”);
– rs.updateDate (“Arrival_Date”, m_date);
• Like “get” methods
– update[Type_name]
– always the Java type
– column name or number
– new value
Meta Data
• Meta data is the information about the datab
ase:
– e.g. the number of columns, the types of the col
umns
– meta data is the schema information

meta data
ID Name Course Mark
A101 Rahul Kumar CCSPM 39
A201 Kiran Kumar CCSPM 39
Accessing Meta Data

• The getMetaData() method can be used o


n a ResultSet object to create its meta dat
a object.
• e.g.
ResultSetMetaData md =
rs.getMetaData();
Using Meta Data

int numCols = md.getColumnCount();

for (int i = 0; i <= numCols; i++) {


if (md.getColumnType(i) ==
Types.CHAR)
System.out.println(
md.getColumnName(i) )
}
Thank You

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