Java Database Connectivity
Agenda
Basics& Introduction
JDBC Goals
JDBC Architecture
Databases
The JDBC Drivers & Types of Drivers
The Basic Steps of JDBC Application
Prepared Statements & Callable Statements
The Transactions & Commitment control
Resources
JDBC - Basics
JDBC is a Java language common database
programming API that provides easy access to the
Database for all the DDL and DML operations.
JDBC provides a standard library for accessing
relational databases.
As well the application developed for certain
database can be easily configured for other
databases.
3
Introduction
JDBC – API standardizes
• Way to establish connection to database
• Approach to initiating queries
• Method to create stored (parameterized) queries
• The data structure of query result (table)
JDBC – API does not standardize SQL
syntax
JDBC classes are in the java.sql &
javax.sql packages
JDBC Goals
SQL-Level
100% Pure Java
Simple to incorporate
High-performance
Leverage existing database technology
Reusability
Why 100% JAVA ??
Write once, run anywhere - Multiple client and server platforms
Object-relational mapping
◦ databases optimized for searching/indexing
◦ objects optimized for engineering/flexibility
Network independence - Works across Internet Protocol
Database independence - Java can access any database vendor
Ease of administration - zero-install client
JDBC Architecture
Application JDBC Driver
Java code calls JDBC library
JDBC loads a driver
Driver talks to a particular database
Ability to have more than one driver to more than one database
Flexibility to change database engines without changing any application
code
JDBC Architecture
Relational Databases
Invented by Dr. E.F.Codd
Data stored in records which live in
tables
Maps row (record) to column (field) in a
single table
“relation” (as in “relational”) means row
to column (not table to table)
Relational (SQL) (RDBMS)
◦ row, column
◦ most popular
Copyright © 1997 Alex Chaffee
SQL
Structured Query Language
Standardized syntax for “querying” (accessing)
a relational database
Supposedly database-independent
Actually, there are important variations from DB
to DB
Copyright © 1997 Alex Chaffee
SQL Syntax
INSERT INTO table ( field1, field2 ) VALUES
( value1, value2 )
◦ inserts a new record into the named table
UPDATE table SET field1 = value1, field2 =
value2 WHERE condition
◦ changes an existing record or records
DELETE FROM table WHERE condition
◦ removes all records that match condition
SELECT field1, field2 FROM table WHERE
condition
◦ retrieves all records that match condition
Copyright © 1997 Alex Chaffee
JDBC Drivers
There are four major JDBC Driver Types
Type I: “Bridge” - JDBC-ODBC bridge plus ODBC driver
Type II: “Native” - Native-API partly Java driver
Type III: “Middleware” - JDBC-Net pure Java driver
Type IV: “Pure” - Native-protocol pure Java driver
JDBC Drivers
Type I ODBC
ODBC
“Bridge” Driver
Type II
JDBC CLI (.lib)
“Native”
Type III Middleware
“Middleware” Server
Type IV
“Pure”
Copyright © 1997 Alex Chaffee
Type I Drivers
Uses bridging technology
Requires
installation/configuration on
client machines
Not preferable for Web
applications
Ex. ODBC Bridge
Copyright © 1997 Alex Chaffee
Type II Drivers
Native API drivers
Requires
installation/configuration on
client machines
Usually not thread-safe
Mostly obsolete now
Ex.Intersolv Oracle Driver,
WebLogic drivers, OCLI
Copyright © 1997 Alex Chaffee
Type III Drivers
Callsmiddleware server, usually
on database host
Very flexible -- allows access to
multiple databases using one
driver
Only need is to download one
driver
But requires another server
application to install and
maintain
e.g. Symantec DBAnywhere
Copyright © 1997 Alex Chaffee
Type IV Drivers
100% Pure Java
Uses Java networking libraries
to talk directly to database
engines
Only disadvantage: need to
download a new driver for each
database engine
e.g. Oracle, mSQL, AS400
Copyright © 1997 Alex Chaffee
The Steps of JDBC Application
Here are the steps for a basic JDBC application
• Step 1 - Load the driver
• Step 2 - Create a database connection
• Step 3 - Create a statement
• Step 4 - Execute the statement(s)
• Step 5 - Process the results
• Step 6 - Close the resources
Step 1 - Loading a Driver
The Driver(s) must be registered with the DriverManager.
The most common used method is to “manually” load it.
import java.sql.*;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();
Class.forName(“com.oracle.jdbc.OracleDriver").newInstance();
} catch (ClassNotFoundException ex) { ex.printStackTrace(); }
// two drivers now registered with the DriverManager
• The driver is supplied by the vendor and must be on the classpath.
• The driver class name(s) can be read from a config file (Java properties
or XML) instead of hard coding in the application
• An alternate method of loading the driver is via a properties file.
DriverManager
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!
Registering a Driver
We can statically load driver
Class.forName(“foo.bar.MyDriver”);
Connection c = DriverManager.getConnection(...);
We can use the jdbc.drivers system property
Copyright © 1997 Alex Chaffee
JDBC Object Classes
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
Copyright © 1997 Alex Chaffee
JDBC Class Usage
DriverManager
Driver
Connection
Statement
ResultSet
Copyright © 1997 Alex Chaffee
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:Northwind
jdbc:msql://host[:port]/database
◦ e.g. jdbc:msql://foo.nowhere.com:4333/accounting
FOR AS400 Connectivity :
◦ Class.forName("com.ibm.as400.access.AS400JDBCDriver");
◦ URL = "jdbc:as400://mySystem;naming=sql;errors=full"
◦ Database Default Port is 8471 (9471)
Copyright © 1997 Alex Chaffee
Step 2 – Create a Connection
Create an instance of a Connection by using the getConnection() from
the DriverManager.
The arguments required are: a database URL, userid and password.
import java.sql.*;
static final String url = "jdbc:odbc:ExampleDB_JavaCourse";
static final String user = “guest";
static final String password = “guestpassword";
Connection dbConnection =
DriverManager.getConnection(url, user,password);
The DriverManager will select the appropriate driver and setup the
DB connection.
If the DB does not require a user and password then use blanks.
static final String user = “"; static final String password = “";
Step 3 - Create a statement
There are three JDBC statement classes.
• Statement-- Basic SQL statements
• PreparedStatement- Precompiled SQL for improved
quality
• CallableStatement--To execute stored procedures in
the database
Statement class is used to execute basic SQL statements.
Step 3 - Create a statement
import java.sql.*;
static final String url = "jdbc:odbc:ExampleDB_JavaCourse";
static final String user = “"; static final String password = “";
// Step 1 – load the driver
try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();
} catch (ClassNotFoundException ex) { ex.printStackTrace(); }
// Step 2 – create a Connection object
Connection dbConnection =
DriverManager.getConnection(url, user,password);
// Step 3 – create a Statement object
Statement stmt = dbConnection.createStatement();
Step 4 - Execute a statement
Executing a query is an operation frequently performed
on a database so will use this as our example. The result
of executing this query is that a result set containing the
requested information will be returned.
// Step 3 – create a Statement object
Statement stmt = dbConnection.createStatement();
// Step 4 – use the Statement object to execute SQL
String query = “select firstname from students”;
ResultSet rs = stmt.executeQuery(query);
Step 5 - Processing a Result Set
// Step 3 – create a Statement object
Statement stmt = dbConnection.createStatement();
// Step 4 – use the Statement object to execute SQL
String query = “select FirstName from students”;
ResultSet rs = stmt.executeQuery(query);
//Step 5 – process the results – row by row
while( rs.next() ) {
System.out.println(rs.getString(“FirstName”));
}
• A result set can be viewed as a table of data containing rows as a result of a
query.
• The cursor is initially positioned before the first row.
• The columns returns are those specified in the query.
Step 6 - Closure
At program termination we would close the objects to ensure that
database resources are released.
Connection dbConnection =
DriverManager.getConnection(url,user, password);
Statement stmt = dbConnection.createStatement();
String query = “select FirstName from students”;
ResultSet rs = stmt.executeQuery(query);
while(rs.next()) {
System.out.println(rs.getString(“FirstName”));
}
rs.close();
stmt.close();
dbConnection.close();
Summary of all the steps
The steps for a basic JDBC program
1. Load the driver – register with DriverManager
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").
2. Create a database connection
Connection dbConnection =
DriverManager.getConnection(url,user, password);
3. Create a statement
Statement stmt = dbConnection.createStatement();
4. Execute the statement(s)
stmt.executeQuery(query); stmt.executeUpdate(anUpdate);
5. Process the results
6. Close - rs.close(); stmt.close(); dbConnection.close();
ResultSet & ResultSetMetaData
Executing an SQL query returns a ResultSet
• The ResultSet can be viewed as a table containing the columns
specified in the query.
• The cursor is initially positioned before first row.
The result set can be traversed only in the forward direction via
the next() method.The result set can be traversed only once
ResultSetMetaData = rs.getMetaData()
Contains all the info about Table column count, column labels
etc;
Useful for generic implementation
Traversing a Result Set
String query = “select FirstName from students”;
ResultSet rs = stmt.executeQuery(query);
// Step 5 – process the results – row by row
while(rs.next()) {
System.out.println(rs.getString(“FirstName”));
}
• A result set is a table of data containing rows as a result of a query.
• The cursor is initially positioned before the first row.
• The columns returns are those specified in the query.
Processing a ResultSet– Getting Data
The data in the table/result set are SQL data types. When a
value is retrieved it is “converted” to a Java type.
• Individual columns values are read using one of the getXXX()
methods. (e.g. getString(), getLong(), getDate(), etc.)
• There are two versions of each getXXX() method:
• one that takes the case-insensitive String name of the column
• one that takes an SQL-style column index;
(column numbers begin at 1)
//Process the results – row by row
while(rs.next()) {
text = rs.getString(1);
text = rs.getString(“firstname”);
}
Getting Data Generically
Each getXXX() method will make reasonable type conversions when
the type of the method does not match the type of the column. For
example, rs.getString(“Price”) converts the floating-point value of a
Price column to a string.
• The type conversions are performed by the JDBC driver.
• getObject() is the most generic of the getXXX() methods. getString()
is fairly generic
// Price column contains a SQL FLOAT (java.sql.Types.FLOAT)
float priceAsPrimitive;
String priceAsString;
Float priceAsFloat;
while(rs.next()) {
priceAsString = rs.getString(“Price”);
priceAsPrimitive = rs.getFloat( “Price”);
priceAsFloat = rs.getObject(“Price”);
}
Mapping Java Types to SQL Types
SQL type Java Type____________
CHAR, VARCHAR, LONGVARCHARString
NUMERIC, DECIMAL java.math.BigDecimal
BIT boolean
TINYINT byte
SMALLINT short
INTEGER int
BIGINT long
REAL float
FLOAT, DOUBLE double
BINARY, VARBINARY, LONGVARBINARY byte[]
DATE java.sql.Date
TIME java.sql.Time
TIMESTAMP java.sql.Timestamp
Copyright © 1997 Alex Chaffee
JDBC - statement.executeUpdate()
public void actionPerformed(ActionEvent evt) {
String name = theName.getText();
String email = theEmail.getText();
String SQLupdate = "Update Students Set emailname
= '" + email + "' " +
"Where FirstName = '" + name + "'"; // single
quotes
Statement stmt = theConnection.createStatement();
int n = stmt.executeUpdate(SQLupdate);
if (n == 0) { System.out.println(“No rows updated”); }
JDBC - PreparedStatement
There are three JDBC statement classes.
• Statement
• Basic SQL statements
• PreparedStatement
• Precompiled SQL for improved performance
• CallableStatement
• To execute stored procedures in the database
JDBC - PreparedStatement
When the database engine executes a SQL query via
executeQuery() it must process the SQL statement.
Processing includes parsing and optimizing the SQL
statement.
• Parsing – checking syntax, are the objects (table
names, etc) in the DB, are the data conversion legal
• Optimizing – finding the best access path
If the SQL statement is used frequently then doing the
overhead processing in advance (“preparing”) can
improve performance.
(approx. 2 to 10 times faster depending on the
complexity of the SQL statement, number of iterations,
etc.)
JDBC - PreparedStatement
The Connection object performs the parsing/preparation.
• The PreparedStatement has place-holders for the parameters that will
be used when the statement is executed.
• The values for the parameters are set using one of the setXXX() methods.
Assume we have a table to keep track of student assignments. The value of
an assignment is a grade. We want to get the value of all assignments for a
given student.
String query1 = “select assgn1, assgn2, assgn3 from
studentAssignments where firstname = ? and lastname = ?”;
PreparedStatement ps1 = conn.prepareStatement(query1);
ps1.setString(1, “John”); ps1.setString(2, “Doe”);
ResultSet rs = ps1.executeQuery();
Callable Statement Example
String createProcedure = "create procedure SHOW_STUDENTS“ +
“as select NAME from STUDENTS order by NAME;";
Statement stmt = con.createStatement();
stmt.executeUpdate(createProcedure);
CallableStatement cs = con.prepareCall("{call
SHOW_STUDENTS}");
ResultSet rs = cs.executeQuery();
• Syntax for creating procedures differs on different DBMS
• Different DBMS support creation of different procedures
Callable statements
CallableStatement is a subclass of PreparedStatement
It can take input parameters
String callProcedure = “{call insertUsers(?)}”;
CallableStatement cs = con.prepareCall(callProcedure);
cs.setString(1, “Tom Cruise");
cs.execute();
It can also return output parameters
String callProcedure = “{call isValidUser (?,?)}”;
CallableStatement cs = con.prepareCall(callProcedure );
cs.setString(1, “Tom Cruise");
cs.registerOutParameter(2, java.sql.Types.integer);
cs.execute();
integer i = cs.getInteger(2);
Summary of Statements
Statement –
◦ For simple SQL statements (no parameters)
◦ Good for statements that are run once
PreparedStatement –
◦ For SQL statements with one or more input parameters
◦ Good for simple SQL statements that are executed
frequently
CallableStatement –
◦ For executing SQL stored procedures
◦ Last longer than program itself
Optimized Statements
Prepared Statements
◦ SQL calls you make again and again
◦ allows driver to optimize (compile) queries
◦ created with Connection.prepareStatement()
Stored Procedures
◦ written in DB-specific language
◦ stored inside database
◦ accesed with Connection.prepareCall()
Copyright © 1997 Alex Chaffee
Transactions
Transaction = more than one statement which
must all succeed (or all fail) together
Ifone fails, the system must reverse all previous
actions
Also can’t leave DB in inconsistent state
halfway through a transaction
◦ COMMIT = complete transaction
◦ ROLLBACK = abort
Copyright © 1997 Alex Chaffee
JDBC - Transactions
There are situations in which we must treat a number of
DB operations (queries, updates) as an atomic action. –
“Either All or None”
Must update more than one table. If one update fails
then want to back out change changes that have already
been posted.
Two users/threads may be operating on the same set of
data. Similar to synchronizing threads, create an atomic
action.
These atomic actions are achieved by using
Transactions.
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
Connection.setAutoCommit(boolean)
If AutoCommit is false, then every statement is
added to an ongoing transaction
We must explicitly commit or rollback the
transaction using Connection.commit() and
Connection.rollback()
Copyright © 1997 Alex Chaffee
Transaction – ISOLATION
READ UNCOMMITTED
When it's used, DBMS will not issue shared locks while
reading data.
This isolation level is also called dirty read. This is the lowest
isolation level.
READ COMMITTED
This is the default isolation level in DBMS. DBMS will use
shared locks while reading data. It ensures that it will never
read data that another application has changed and not yet
committed. It does not ensure that the data will not be
changed before the end of the transaction.
Transaction – ISOLATION
REPEATABLE READ
When it's used, then dirty reads and nonrepeatable reads
cannot occur. It means that locks will be placed on all
data that is used in a query, and another transactions
cannot update the data.
SERIALIZABLE
Most restrictive isolation level. When it's used, then
phantom values cannot occur. It prevents other users
from updating or inserting rows into the data set until
the transaction is complete.
JDBC - Transactions
A transactions consists of a group of operations.
• The transactions is only permanently posted to the database if it is
committed. If the program terminates abnormally the transaction is
automatically rolled back.
• By default each JDBC operations occur in a transaction that is
automatically committed.
try {
conn.setAutoCommit(false);// default commits each operation
stmt.executeQuery(aQuery);
stmt.executeUpdate(updateOne);
stmt.executeQuery(updateTwo);
conn.commit(); // Commit the transaction
}
catch( SQLException se) {
conn.rollback(); // back out changes temporarily posted
}
JDBC Class Diagram
Copyright © 1997 Alex Chaffee
Resources
Reese, Database Programming with JDBC and
Java (O’Reilly)
http://java.sun.com/products/jdbc/
http://java.sun.com/products/java-blend/
http://www.purpletech.com/java/
List of Available JDBC Drivers
–
http://industry.java.sun.com/products/jdbc/drivers
/
API for java.sql
–
http://java.sun.com/j2se/1.4/docs/api/java/sql/pac
kage-summary.html
Copyright © 1997 Alex Chaffee
Questions ???
Thank You