JDBC
JDBC
ODBC
API
JDBC Drivers
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 (JavaCSQL) 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
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
• 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
• 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
Reservations table
meta data
ID Name Course Mark
A101 Rahul Kumar CCSPM 39
A201 Kiran Kumar CCSPM 39
Accessing Meta Data