You are on page 1of 72

JDBC and Database Programming in Java

Alexander Day Chaffee alexc@purpletech.com

Copyright 1997 Alex Chaffee

Version 1.1, 14 Feb 98

Introduction
Database Access in Java x Find out any relevant background and interest of the audience
x
x SQL

gurus? x Visual Basic Database Forms?

Copyright 1997 Alex Chaffee

Agenda
Overview of Databases and Java x Overview of JDBC x JDBC APIs x Other Database Techniques
x

Copyright 1997 Alex Chaffee

Overview
RMI JDBC CORBA

java.net

TCP/IP

Network OS
Copyright 1997 Alex Chaffee

Vocabulary
Glossary of terms x Define the terms as used in this subject
x

Copyright 1997 Alex Chaffee

Part I: Overview of Databases and Java

Copyright 1997 Alex Chaffee

Databases in the Enterprise


All corporate data stored in DB x SQL standardizes format (sort of)
x

Copyright 1997 Alex Chaffee

Why Java?
x

Write once, run anywhere


x

Multiple client and server platforms databases optimized for searching/indexing objects optimized for engineering/flexibility Works across Internet Protocol Java can access any database vendor zero-install client
Copyright 1997 Alex Chaffee

Object-relational mapping
x x

Network independence
x

Database independence
x

Ease of administration
x

Database Architectures
Two-tier x Three-tier x N-tier
x

Copyright 1997 Alex Chaffee

Two-Tier Architecture
Client connects directly to server x e.g. HTTP, email x Pro:
x
x simple x client-side

scripting offloads work onto the

client
x

Con:
x fat

client x inflexible

Copyright 1997 Alex Chaffee

Three-Tier Architecture
x

Application Server sits between client and database

Copyright 1997 Alex Chaffee

Three-Tier Pros
flexible: can change one part without affecting others x can connect to different databases without changing code x specialization: presentation / business logic / data management x can cache queries x can implement proxies and firewalls
x
Copyright 1997 Alex Chaffee

Three-Tier Cons
higher complexity x higher maintenance x lower network efficiency x more parts to configure (and buy)
x

Copyright 1997 Alex Chaffee

N-Tier Architecture
Design your application using as many tiers as you need x Use Object-Oriented Design techniques x Put the various components on whatever host makes sense x Java allows N-Tier Architecture, especially with RMI and JDBC
x
Copyright 1997 Alex Chaffee

Database Technologies
x

Hierarchical
x x

obsolete (in a manner of speaking) any specialized file format can be called a hierarchical DB row, column most popular add inheritance, blobs to RDB NOT object-oriented -- object is mostly a marketing term data stored as objects high-performance for OO data models
Copyright 1997 Alex Chaffee

Relational (aka SQL) (RDBMS)


x x

Object-relational DB (ORDBMS)
x x

Object-oriented DB (OODB)
x x

Relational Databases
invented by Dr. E.F.Codd x data stored in records which live in tables x maps row (record) to column (field) in a single table x relation (as in relational) means row to column (not table to table)
x

Copyright 1997 Alex Chaffee

Joining Tables
you can associate tables with one another x allows data to nest x allows arbitrarily complicated data structures x not object-oriented
x

Copyright 1997 Alex Chaffee

Join example
x

People
x name x homeaddress x workaddress

Addresses
x id x street x state x zip
Copyright 1997 Alex Chaffee

SQL
Structured Query Language x Standardized syntax for querying (accessing) a relational database x Supposedly database-independent x Actually, there are important variations from DB to DB
x

Copyright 1997 Alex Chaffee

SQL Syntax
INSERT INTO table ( field1, field2 ) VALUES ( value1, value2 ) x inserts a new record into the named table UPDATE table SET ( field1 = value1, field2 = value2 ) WHERE condition x changes an existing record or records DELETE FROM table WHERE condition x removes all records that match condition SELECT field1, field2 FROM table WHERE condition x retrieves all records that match condition
Copyright 1997 Alex Chaffee

Transactions
Transaction = more than one statement which must all succeed (or all fail) together x If one fails, the system must reverse all previous actions x Also cant leave DB in inconsistent state halfway through a transaction x COMMIT = complete transaction x ROLLBACK = abort
x
Copyright 1997 Alex Chaffee

Part II: JDBC Overview

Copyright 1997 Alex Chaffee

JDBC Goals
SQL-Level x 100% Pure Java x Keep it simple x High-performance x Leverage existing database technology
x
x why

reinvent the wheel?

Use strong, static typing wherever possible x Use multiple methods to express multiple Copyright 1997 Alex Chaffee functionality
x

JDBC Ancestry
X/OPEN

ODBC

JDBC

Copyright 1997 Alex Chaffee

JDBC Architecture
Application
x x x x

JDBC

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 Ideal: can change database engines without changing any application code
Copyright 1997 Alex Chaffee

JDBC Drivers
Type I: Bridge x Type II: Native x Type III: Middleware x Type IV: Pure
x

Copyright 1997 Alex Chaffee

JDBC Drivers (Fig.)


Type I Bridge JDBC Type II Native Type III Middleware Type IV Pure
Copyright 1997 Alex Chaffee

ODBC

ODBC Driver

CLI (.lib) Middleware Server

Type I Drivers
Use bridging technology x Requires installation/configuration on client machines x Not good for Web x e.g. ODBC Bridge
x

Copyright 1997 Alex Chaffee

Type II Drivers
Native API drivers x Requires installation/configuration on client machines x Used to leverage existing CLI libraries x Usually not thread-safe x Mostly obsolete now x e.g. Intersolv Oracle Driver, WebLogic drivers
x
Copyright 1997 Alex Chaffee

Type III Drivers


Calls middleware server, usually on database host x Very flexible -- allows access to multiple databases using one driver x Only need to download one driver x But its another server application to install and maintain x e.g. Symantec DBAnywhere
x
Copyright 1997 Alex Chaffee

Type IV Drivers
100% Pure Java -- the Holy Grail x Use Java networking libraries to talk directly to database engines x Only disadvantage: need to download a new driver for each database engine x e.g. Oracle, mSQL
x

Copyright 1997 Alex Chaffee

JDBC Limitations
No scrolling cursors x No bookmarks
x

Copyright 1997 Alex Chaffee

Related Technologies
x

ODBC
x Requires

configuration (odbc.ini) Win32

RDO, ADO
x Requires

OODB
x e.g.

ObjectStore from ODI objects to tables transparently (more or


Copyright 1997 Alex Chaffee

JavaBlend
x maps

less)

Part III: JDBC APIs

Copyright 1997 Alex Chaffee

java.sql
x

JDBC is implemented via classes in the java.sql package

Copyright 1997 Alex Chaffee

Loading a Driver Directly


Driver d = new foo.bar.MyDriver(); Connection c = d.connect(...); x Not recommended, use DriverManager instead x Useful if you know you want a particular driver
Copyright 1997 Alex Chaffee

DriverManager
DriverManager tries all the drivers x Uses the first one that works x When a driver class is first loaded, it registers itself with the DriverManager x Therefore, to register a driver, just load it!
x

Copyright 1997 Alex Chaffee

Registering a Driver
x

statically load driver

Class.forName(foo.bar.MyDriver); Connection c = DriverManager.getConnection(...);


x

or use the jdbc.drivers system property

Copyright 1997 Alex Chaffee

JDBC Object Classes


x

DriverManager
x

Loads, chooses drivers connects to actual database a series of SQL statements to and from the DB a single SQL statement the records returned from a Statement

Driver
x

Connection
x

Statement
x

ResultSet
x
Copyright 1997 Alex Chaffee

JDBC Class Usage


DriverManager Driver Connection Statement ResultSet
Copyright 1997 Alex Chaffee

JDBC URLs
jdbc:subprotocol:source x each driver has its own subprotocol x each subprotocol has its own syntax for the source
jdbc:odbc:DataSource
x

e.g. jdbc:odbc:Northwind e.g. jdbc:msql://foo.nowhere.com:4333/accounting


Copyright 1997 Alex Chaffee

jdbc:msql://host[:port]/database
x

DriverManager
Connection getConnection (String url, String user, String password) x Connects to given JDBC URL with given user name and password x Throws java.sql.SQLException x returns a Connection object
Copyright 1997 Alex Chaffee

Connection
x x

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 x NB: Some drivers dont support serialized connections x Fortunately, most do (now) Also provides metadata -- information about the database, tables, and fields Also methods to deal with transactions
Copyright 1997 Alex Chaffee

Obtaining a Connection
String url = "jdbc:odbc:Northwind"; try { Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver"); Connection con = DriverManager.getConnection(url); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); }

Copyright 1997 Alex Chaffee

Connection Methods
Statement createStatement()
x

returns a new Statement object

PreparedStatement prepareStatement(String sql)


x

returns a new PreparedStatement object returns a new CallableStatement object

CallableStatement prepareCall(String sql)


x

Why all these different kinds of statements? Optimization.


Copyright 1997 Alex Chaffee

Statement
x

A Statement object is used for executing a static SQL statement and obtaining the results produced by it.

Copyright 1997 Alex Chaffee

Statement Methods
ResultSet executeQuery(String)
x

Execute a SQL statement that returns a single ResultSet. Execute a SQL INSERT, UPDATE or DELETE statement. Returns the number of rows changed. Execute a SQL statement that may return multiple results.

int executeUpdate(String)
x

boolean execute(String)
x

Why all these different kinds of queries? Optimization. Copyright 1997 Alex Chaffee

ResultSet
x x

x x

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 to its current row of data. The 'next' method moves the cursor to the next row.
x

you cant rewind


Copyright 1997 Alex Chaffee

ResultSet Methods
x

boolean next()
x activates

the next row x the first call to next() activates the first row x returns false if there are no more rows
x

void close()
x disposes

of the ResultSet x allows you to re-use the Statement that created it x automatically called by most Statement Copyright 1997 Alex Chaffee methods

ResultSet Methods
x

Type getType(int columnIndex)


x returns

the given field as the given type x fields indexed starting at 1 (not 0)
x

Type getType(String columnName)


x same,

but uses name of field x less efficient


x

int findColumn(String columnName)


x looks

up column index given column name


Copyright 1997 Alex Chaffee

ResultSet Methods
x x x x x x x x x x x

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)
Copyright 1997 Alex Chaffee

ResultSet Methods
x x x x x x x x x x x

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)
Copyright 1997 Alex Chaffee

isNull
In SQL, NULL means the field is empty x Not the same as 0 or x In JDBC, you must explicitly ask if a field is null by calling ResultSet.isNull(column)
x

Copyright 1997 Alex Chaffee

Sample Database
Employee ID 1 2 3 4 5 Last Name Davolio Fuller Leverling Peacock Buchanan First Name Nancy Andrew Janet Margaret Steven

Copyright 1997 Alex Chaffee

SELECT Example
Connection con = DriverManager.getConnection(url, "alex", "8675309"); Statement st = con.createStatement(); ResultSet results = st.executeQuery("SELECT EmployeeID, LastName, FirstName FROM Employees");

Copyright 1997 Alex Chaffee

SELECT Example (Cont.)


while (results.next()) { int id = results.getInt(1); String last = results.getString(2); String first = results.getString(3); System.out.println("" + id + ": " + first + " " + last); } st.close(); con.close();
Copyright 1997 Alex Chaffee

Mapping Java Types to SQL Types


SQL type CHAR, VARCHAR, LONGVARCHAR NUMERIC, DECIMAL BIT TINYINT SMALLINT INTEGER BIGINT REAL FLOAT, DOUBLE BINARY, VARBINARY, LONGVARBINARY DATE TIME TIMESTAMP Java Type String java.math.BigDecimal boolean byte short int long float double byte[] java.sql.Date java.sql.Time java.sql.Timestamp
Copyright 1997 Alex Chaffee

Database Time
x x x

Times in SQL are notoriously unstandard Java defines three classes to help java.sql.Date
x

year, month, day hours, minutes, seconds year, month, day, hours, minutes, seconds, nanoseconds usually use this one
Copyright 1997 Alex Chaffee

java.sql.Time
x

java.sql.Timestamp
x x

Modifying the Database


use executeUpdate if the SQL contains INSERT or UPDATE x Why isnt it smart enough to parse the SQL? Optimization. x executeUpdate returns the number of rows modified x executeUpdate also used for CREATE TABLE etc. (DDL)
x
Copyright 1997 Alex Chaffee

INSERT example

Copyright 1997 Alex Chaffee

Transaction Management
Transactions are not explicitly opened and closed x Instead, the connection has a state called AutoCommit mode x if AutoCommit is true, then every statement is automatically committed x default case: true
x
Copyright 1997 Alex Chaffee

setAutoCommit
Connection.setAutoCommit(boolean) x if AutoCommit is false, then every statement is added to an ongoing transaction x you must explicitly commit or rollback the transaction using Connection.commit() and Connection.rollback()

Copyright 1997 Alex Chaffee

Connection Managers
x

Hint: for a large threaded database server, create a Connection Manager object It is responsible for maintaining a certain number of open connections to the database When your applications need a connection, they ask for one from the CMs pool Why? Because opening and closing connections takes a long time Warning: the CM should always setAutoCommit(false) when a connection is returned
Copyright 1997 Alex Chaffee

Optimized Statements
x

Prepared Statements
x SQL

calls you make again and again x allows driver to optimize (compile) queries x created with Connection.prepareStatement()
x

Stored Procedures
x written

in DB-specific language x stored inside database x accesed with Connection.prepareCall()


Copyright 1997 Alex Chaffee

JDBC Class Diagram

Whoa!
Copyright 1997 Alex Chaffee

Metadata
x

Connection:
x DatabaseMetaData

getMetaData() getMetaData()

ResultSet:
x ResultSetMetaData

Copyright 1997 Alex Chaffee

ResultSetMetaData
x x x x x x
x x x x x
x x x x

What's the number of columns in the ResultSet? What's a column's name? What's a column's SQL type? What's the column's normal max width in chars? What's the suggested column title for use in printouts and displays? What's a column's number of decimal digits?
Does a column's case matter? Is the column a cash value? Will a write on the column definitely succeed? Can you put a NULL in this column? Is a column definitely not writable?
Can the column be used in a where clause? Is the column a signed number? Is it possible for a write on the column to succeed? and so on...

Copyright 1997 Alex Chaffee

DatabaseMetaData
What tables are available? x What's our user name as known to the database? x Is the database in read-only mode? x If table correlation names are supported, are they restricted to be different from the names of the tables? x and so on
x
Copyright 1997 Alex Chaffee

JavaBlend: Java to Relational Mapping

Copyright 1997 Alex Chaffee

JDBC 2.0
x x x

Scrollable result set Batch updates Advanced data types


x

Blobs, objects, structured types Persistent JavaBeans

Rowsets
x

x x x

JNDI Connection Pooling Distributed transactions via JTS

Summary
State what has been learned x Define ways to apply training x Request feedback of training session
x

Copyright 1997 Alex Chaffee

Where to get more information


Other training sessions x Reese, Database Programming with JDBC and Java (OReilly) x http://java.sun.com/products/jdbc/ x http://java.sun.com/products/java-blend/ x http://www.purpletech.com/java/ (Authors site)
x
Copyright 1997 Alex Chaffee