Download jdbc

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Java Database Connectivity
JDBC
Oct 2002
1
Database Access in Java

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
Oct 2002
2
JDBC






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.
Oct 2002
3
DBMS and Java

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
Oct 2002
4
–
JDBC History
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.

Oct 2002
5
Java Application
JDBC API
Java DB Interaction
- DriverManager
Driver Manager
- Drivers
- Database
JDBC Driver API
JDBC / ODBC
Bridge
Vendor supplied
JDBC Driver
ODBC Driver
Database
Database
Oct 2002
6
JDBC Drivers
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
Oct 2002
7
JDBC Drivers

Type 1
–

Type 2
–

Native API part-Java
Type 3
–

JDBC-ODBC Bridge
All-Java using DBMS-independent net protocol and
middle-ware
Type 4
–
Oct 2002
All Java using DBMS-specific protocol
8
Type 1




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
database
JDBC-ODBC
bridge
ODBC
Driver
Servlet
Code
ODBC
API
Oct 2002
9
Type 2


A type 2 driver uses a Java driver to communicate with a
vendor specific API
Because of the use of native API -> better performance
Vendor specific protocol
database
Oct 2002
JDBC Driver
Part java, part
native code
Servlet
Code
10
Type 3




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
Oct 2002
11
Type 4



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
Vendor specific protocol
database
Oct 2002
JDBC Driver
Part java
Servlet
Code
12
JDBC

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 functionality (for
example, date literals)
Can use DatabaseMetaData to adapt to particular
underlying database
–
–
–
Oct 2002
13
Basic JDBC Objects

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.*:
–
Oct 2002
Datasource - used for Enterprise resource
connections and data pooling.
14
Coding JDBC

There are 7 steps used to access a database using
Java:
–
–
–
–
–
–
–
Oct 2002
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
15
JDBC Driver Load/Install (Step 1)

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”);
Oct 2002
16
The JDBC Connection 1
(Step 2)


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:
–
Oct 2002
jdbc:<subprotocol>:<subname>
17
JDBC Connection
(Step 2)

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";
Oct 2002
18
The JDBC Connection 2
(Step 2)

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";
Oct 2002
19
Make the Connection
Step 3

Use DriverManager to match the driver to the
database server
–
Must be caught
Connection con = null;
con = DriverManager.getConnection(url, “id","passwd");
Oct 2002
20
JDBC Connection
Overview
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

Oct 2002
21
JDBC Connection
Overview

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
Oct 2002
22
The JDBC Statement
(Step 4)
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.

Oct 2002
23
JDBC Statement



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();
Oct 2002
24
JDBC

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
Class
Statement
Connection Type
createStatement()
About
Use for simple SQL statements with
no input parameters
Prepared
Statement
preparedStatement()
Calleable
Statement
prepareCall()
Pre-compiled; Can take input
parameters Use for simple SQL
statements executed often,
statements with input parameters
Use to execute stored procedures
Oct 2002
25
Execute the Query
(Step 5)

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");
Oct 2002
26
Process the Result
Step 6

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);
}
Oct 2002
27
Close the Connection
Step 7

Opening and closing connection is
processing intensive!
rs.close();
stmt.close();
con.close();
Oct 2002
28
Diagram of Java/DB interaction
DriveManager
creates
Connection
creates
Statement
creates
ResultSet
SQL
make link
to driver
data
Driver
data
SQL
Database
Oct 2002
29
Exception Handling
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
•
–
Oct 2002
SQL syntax, CRUD errors, etc
Has additional methods specifically for dealing
with DB errors
30
More on Exceptions

Cont. SQLException:
–
getSQLState() - returns an SQLState identifier
•
–
–
–
Oct 2002
See DB manuals for identification
getErrorCode() - get vendor specific error code
getNextException() - Examination of multiple
errors
setNextException() - Add an exception to the
chain
31
Still More on Exceptions

Example:
try {
// some DB work
} catch ( SQLException sqlex) {
while( sqlex != null) {
// do handling
sqlex = sqlex.getNextException();
}
} // end catch
Oct 2002
32
SQL Warnings

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

Oct 2002
33
SQLWarning Example
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
Oct 2002
34
SQL

Mapping SQL Data Types
–
Java primitives & classes
–
Java plus JDBC data types provide excellent
mapping
–
BigDecimal
–
Date, Time and TimeStamp
Oct 2002
35
Java - SQL Types
SQL Type
Java Type
SQL Description
SMALLINT
INTEGER
BIGINT
REAL
DOUBLE
DECIMAL
CHAR
short
int
long
float
double
BigDecimal
String
16 bit signed integer
32 bit signed integer
64 bit signed integer
single precision float
double precision float
packed decimal
fixed length strings
Oct 2002
36
Java – SQL Types
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
Oct 2002
37