Sep 2003
JDBC
1
Sequential file access, such as we have just seen, is essentially a one-tier architecture
–
One-tier = The user’s code contains details of the actual storage format on the local machine
Today’s approaches to persistent storage demand two, three and n-tier architectures
In these newer architectures persistent storage is removed from the local machine and transferred to a backend DBMS
Sep 2003 2
Standardized SQL lets you talk to databases from different vendors in a uniform way.
ODBC defined a standard C interface for talking to databases with
SQL.
The JDBC (Java Database Connectivity) library (java.sql) allows you to use SQL to talk to databases from a Java program.
The java.sql calls go through a JDBC driver.
JDK comes with a JDBC to ODBC bridge.
DB vendors are creating native JDBC drivers; JDBC drivers that talk over a network also exist.
Sep 2003 3
Over the years many DBMS “standards” have evolved.
–
–
Fortunately they are almost all based on SQL
Unfortunately there is no single SQL standard.
Java’s goal is to provide a set of standard classes, the JDBC, that merge these dialects
–
Goals are similar to Microsoft’s ODBC
–
The translation details are taken care of by dynamically installable device drivers
Sep 2003 4
The JDBC API was released with version
1.1 of Java
JDBC was modeled on Microsoft’s successful ODBC. One is not derived from the other: both are based on X/Open SQL standards.
Sep 2003 5
Java DB Interaction
- DriverManager
- Drivers
- Database
Sep 2003
Java Application
JDBC API
Driver Manager
JDBC Driver API
JDBC / ODBC
Bridge
Vendor supplied
JDBC Driver
ODBC Driver
Database
Database
6
You don’t have to write the drivers that implement JDBC for a given database system. DBMS vendors do this.
Which drivers exist? A list is maintained by sun:
– http://java.sun.com/products/jdbc/jdbc.drivers.html
There are four categories of drivers, as discussed on Sun’s pages
Sep 2003 7
Type 1
–
JDBC-ODBC Bridge
Type 2
–
Native API part-Java
Type 3
–
All-Java using DBMS-independent net protocol and middle-ware
Type 4
–
All Java using DBMS-specific protocol
Sep 2003 8
Defines the JDBC to ODBC (MS-Access, local defined ODBC)
The driver translates standard JDBC calls to a corresponding
ODBC call and sends it to the ODBC data source via the windows
ODBC libraries
Inefficient, system calls through multiple layers
Functionality is also limited by the ODBC interface
ODBC
Driver
JDBC-ODBC bridge database
Servlet
Code
ODBC
API
Sep 2003 9
A type 2 driver uses a Java driver to communicate with a vendor specific API
Because of the use of native API -> better performance database
Vendor specific protocol
JDBC Driver
Part java, part native code
Servlet
Code
Sep 2003 10
All java driver and an all java middle tier
Your program sends a JDBC call through the JDB driver to the middle tier without translation. The middle tier uses another jdbc driver to complete the request
Middle tier may use type 1 or 2 driver
Rare third party implementations: Inprise, intersolv
Type 1 or 2
Driver
Database
Access Server
JDBC driver Servlet
Code database
Sep 2003 11
An all java driver that issues requests directly to the database
Simplest to deploy, no additional libraries and middleware to install
All major vendors provide type 4 JDBC drivers for their databases – Oracle etc database
Vendor specific protocol
JDBC Driver
Part java
Sep 2003
Servlet
Code
12
Sep 2003
SQL Variety
–
Although SQL is a standard, only basic functionality is broadly and uniformly supported
–
–
For example, not all DB vendors support stored procedures or outer joins
JDBC passes any query string through to the DBMS
–
–
JDBC "escape syntax" provides a standard way to access common non-standard functionalit y (for example, date literals)
Can use DatabaseMetaData to adapt to particular underlying database
13
java.sql.*:
–
DriverManager - organized JDBC drivers
–
–
–
–
Connection - actual database connection
Statement - simple SQL string for execution
PreparedStatement - precompiled SQL string
ResultSet - resultant dataset
javax.sql.*:
–
Datasource - used for Enterprise resource connections and data pooling.
Sep 2003 14
There are 7 steps used to access a database using
Java:
–
–
–
–
–
–
–
Load the driver
Define the Connection
Make a Connection to the database
Create a Statement object
Execute a Query/Update/Insert etc
Process the results – ResultSet
Close the Connection
Sep 2003 15
Access the DriverManager to get a Connection to the database.
–
–
The DriverManager keeps track of the available Drivers
You force the DriverManager to register a driver
–
When you want a connection, the DriverManager polls the available drivers until one (or none) give it the connection
Coding driver loading
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
Class.forName(“oracle.jdbc.driver.OracleDriver”);
Sep 2003 16
The Connection object uses the list of drivers to establish a physical connection to the data source you specify. The general syntax is
"Conn.open('datasource', 'username', 'password');" where username and password are used to "log in" to the database.
The ‘datasource’ is used to describe the
Connection . It has the format:
– jdbc:<subprotocol>:<subname>
Sep 2003 17
The form of this is slightly different for external databases and for local drivers. Here is the way one would access an external database, the database named
“sample” served up by the myserver.mycompany.com server at port 356:
String url =
"jdbc:dbnet://myserver.mycompany.com:3456/sample";
Sep 2003 18
The format of the “URL” for a local file, say an Access file named “mydb”, reached via the odbc-jdbc bridge, would be:
String url = "jdbc:odbc:mydb";
Sep 2003 19
Use DriverManager to match the driver to the database server
–
Must be caught
Connection con = null; con = DriverManager.getConnection(url, “id","passwd");
Sep 2003 20
The DriverManager tests passes the URL to each registered driver (in order of registration)
The first driver that can handle the URL gets to service the connection
Only drivers loaded via the boot class loader or the class loader that loaded the requesting code are checked
Sep 2003 21
An application can have:
–
–
–
One connection to one database
Multiple connections to the same database
Or multiple connections to different databases
A "connection session" refers to the SQL statements executed and results returned over a connection
Sep 2003 22
The fouth step in JDBC access is to use one of the connection methods to acquire a
Statement object.
The Statement object will contain the SQL query or name of the stored procedure you wish to execute on the open connection.
Sep 2003 23
The Statement object is used to communicate with the DB server (once the client is connected.
The creation of the Statement object doesn’t send a message to the server – that is done next
Example:
Statement stmt = con.createStatement();
Sep 2003 24
3 types of Statements
–
–
Use the connection object to send SQL statements to the database
If underlying database doesn't understand the statement, you'll get an exception
Statement createStatement()
Prepared
Statement preparedStatement()
Calleable
Statement
Sep 2003 prepareCall()
Use for simple SQL statements with no input parameters
Pre-compiled; Can take input parameters Use for simple SQL statements executed often, statements with input parameters
Use to execute stored procedures
25
A method of Statement can be used to send along the SQL query, and get back the resulting table:
ResultSet rs = stmt.executeQuery(
"SELECT a,b,c FROM Table2");
Sep 2003 26
The resulting table can be accessed using methods in ResultSet : while (rs.next()) { int i = rs.getInt("a");
String s = rs.getString("b"); float f = rs.getFloat("c");
System.out.println("ROW = " + i + " " + s + “ " + f);
}
Sep 2003 27
Opening and closing connection is processing intensive!
rs.close(); stmt.close(); con.close();
Sep 2003 28
DriveManager creates
Connection creates
Statement creates
ResultSet
SQL data make link to driver
Driver
SQL data
Database
Sep 2003 29
Most JDBC work must be done inside a
‘try/catch’ block
java.sql.SQLException
–
–
–
–
Thrown by most java.sql.* methods
Extends java.lang.Exception
Intended to describe database or driver errors
•
SQL syntax, CRUD errors, etc
Has additional methods specifically for dealing with DB errors
Sep 2003 30
Cont. SQLException:
–
–
–
– getSQLState() - returns an SQLState identifier
•
See DB manuals for identification getErrorCode() - get vendor specific error code getNextException() - Examination of multiple errors setNextException() - Add an exception to the chain
Sep 2003 31
Example: try {
// some DB work
} catch ( SQLException sqlex) { while( sqlex != null) {
// do handling sqlex = sqlex.getNextException();
}
} // end catch
Sep 2003 32
SQLWarning Class
–
–
Extends SQLException
Is not thrown, developer must ask for warnings
Non-critical error, won’t stop processing
Can be retrieved on Connection,
Statement(s), and ResultSet
May not need to be examined
Sep 2003 33
try { ...
stmt = con.createStatement(); sqlw = con.getWarnings(); while( sqlw != null) {
// handleSQLWarnings sqlw = sqlw.getNextWarning();
} con.clearWarnings(); stmt.executeUpdate( sUpdate ); sqlw = stmt.getWarnings(); while( sqlw != null) {
// handleSQLWarnings sqlw = sqlw.getNextWarning();
}
} catch ( SQLException sqlex) { ... } // end catch
Sep 2003 34
Mapping SQL Data Types
–
Java primitives & classes
–
Java plus JDBC data types provide excellent mapping
–
BigDecimal
–
Date, Time and TimeStamp
Sep 2003 35
SQL Type Java Type
SMALLINT
INTEGER
BIGINT
REAL
DOUBLE
DECIMAL
CHAR
Sep 2003 short int long float double
BigDecimal
String
SQL Description
16 bit signed integer
32 bit signed integer
64 bit signed integer single precision float double precision float packed decimal fixed length strings
36
SQL Type Java Type SQL Description
VARCHAR
DATE
TIME
BLOB
CLOB
DBCLOB short java.sql.Date
java.sql.Time
java.sql.Blob
java.sql.Clob
java.sql.Dbclob
Variable length string
10 byte char string
8 byte char string
Binary object
Large character obj.
Double byte CLOB
Sep 2003 37
Sep 2003
38
Sep 2003
String fname = “John”;
String lname = “Doe”; int num = 123;
String query = “insert into Table1 values(‘” + fname + “’, ‘” + lname + “’, ” + num + “)”;
Statement stmt = con.createStatement(); int rc = stmt.executeUpdate(query ); stmt.close(); con.close();
39
Used for Precompiled Database queries/statements
–
Declare a PreparedStatement object
PreparedStatement ps = con.prepareStatement( String );
Sep 2003 40
String query = “insert into Table1 values (?, ?, ?)”;
PreparedStatement ps = con.prepareStatement(query); ps.setString(1, “John”); ps.setString(2, “Doe”); ps.setInt(3, 123); int rc = ps.executeUpdate(); ps.setString(1, “Mary”); ps.setString(2, “Smith”); ps.setInt(3, 456); rc = ps.executeUpdate(); ps.close(); con.close();
Sep 2003 41
Statement st = con.createStatement(); con.setAutoCommit(false); st.addBatch(“insert into T1 values (‘Bill’, ‘Jones’, 333)”); st.addBatch(“insert into T1 values (‘Sue’, ‘Brown’, 444)”); st.addBatch(“insert into T1 values (‘Joe’, ‘Smith’, 555)”); int []retArr = st.executeBatch();
Sep 2003 42
Transactions
A transaction is a group of statements that will be committed if all goes well, or all rolled back if an error occurs.
They are needed to support database integrity: e.g. when adding a record, we want to be sure that all tables containing information on that record have indeed been updated; if some have not, the entire transaction should be rolled back.
By default a database connection is in autocommit mode, i.e. each SQL command is committed as soon as executed. Thus, for transaction management, we first need to turn off the autocommit mode: con.setAutoCommit(false);
Statement stmt=con.creatStatement(); stmt.executeUpdate(command1); stmt.executeUpdate(command2);
… con.commit(); //if all goes well con.rollback();//if error occurs
Sep 2003 43