+ All Categories

JDBC

Date post: 27-Nov-2014
Category:
Upload: nileshmit
View: 161 times
Download: 2 times
Share this document with a friend
Popular Tags:
72
JDBC and Database JDBC and Database Programming in Java Programming in Java
Transcript
Page 1: JDBC

JDBC and Database JDBC and Database Programming in JavaProgramming in Java

Page 2: JDBC

Copyright © 1997 Alex Chaffee

Introduction Introduction

Database Access in Java Find out any relevant background and

interest of the audience SQL gurus? Visual Basic Database Forms?

Page 3: JDBC

Copyright © 1997 Alex Chaffee

AgendaAgenda

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

Page 4: JDBC

Copyright © 1997 Alex Chaffee

Overview Overview

TCP/IP

java.net

RMI JDBC CORBA

Network OS

Page 5: JDBC

Copyright © 1997 Alex Chaffee

VocabularyVocabulary

Glossary of terms Define the terms as used in this subject

Page 6: JDBC

Copyright © 1997 Alex Chaffee

Part I: Overview of Databases Part I: Overview of Databases and Javaand Java

Page 7: JDBC

Copyright © 1997 Alex Chaffee

Databases in the EnterpriseDatabases in the Enterprise

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

Page 8: JDBC

Copyright © 1997 Alex Chaffee

Why Java?Why 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

Page 9: JDBC

Copyright © 1997 Alex Chaffee

Database ArchitecturesDatabase Architectures

Two-tier Three-tier N-tier

Page 10: JDBC

Copyright © 1997 Alex Chaffee

Two-Tier ArchitectureTwo-Tier Architecture

Client connects directly to server e.g. HTTP, email Pro:

simple client-side scripting offloads work onto the client

Con: fat client inflexible

Page 11: JDBC

Copyright © 1997 Alex Chaffee

Three-Tier ArchitectureThree-Tier Architecture Application Server sits between client and

database

Page 12: JDBC

Copyright © 1997 Alex Chaffee

Three-Tier ProsThree-Tier Pros

flexible: can change one part without affecting others

can connect to different databases without changing code

specialization: presentation / business logic / data management

can cache queries can implement proxies and firewalls

Page 13: JDBC

Copyright © 1997 Alex Chaffee

Three-Tier ConsThree-Tier Cons

higher complexity higher maintenance lower network efficiency more parts to configure (and buy)

Page 14: JDBC

Copyright © 1997 Alex Chaffee

N-Tier ArchitectureN-Tier Architecture

Design your application using as many “tiers” as you need

Use Object-Oriented Design techniques Put the various components on whatever

host makes sense Java allows N-Tier Architecture, especially

with RMI and JDBC

Page 15: JDBC

Copyright © 1997 Alex Chaffee

Database TechnologiesDatabase Technologies Hierarchical

obsolete (in a manner of speaking) any specialized file format can be called a hierarchical DB

Relational (aka SQL) (RDBMS) row, column most popular

Object-relational DB (ORDBMS) add inheritance, blobs to RDB NOT object-oriented -- “object” is mostly a marketing term

Object-oriented DB (OODB) data stored as objects high-performance for OO data models

Page 16: JDBC

Copyright © 1997 Alex Chaffee

Relational DatabasesRelational 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)

Page 17: JDBC

Copyright © 1997 Alex Chaffee

Joining TablesJoining Tables

you can associate tables with one another allows data to nest allows arbitrarily complicated data

structures not object-oriented

Page 18: JDBC

Copyright © 1997 Alex Chaffee

Join exampleJoin example

People name homeaddress workaddress

Addresses id street state zip

Page 19: JDBC

Copyright © 1997 Alex Chaffee

SQLSQL

Structured Query Language Standardized syntax for “querying”

(accessing) a relational database Supposedly database-independent Actually, there are important variations

from DB to DB

Page 20: JDBC

Copyright © 1997 Alex Chaffee

SQL SyntaxSQL SyntaxINSERT 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

Page 21: JDBC

Copyright © 1997 Alex Chaffee

TransactionsTransactions

Transaction = more than one statement which must all succeed (or all fail) together

If one 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

Page 22: JDBC

Copyright © 1997 Alex Chaffee

Part II: JDBC OverviewPart II: JDBC Overview

Page 23: JDBC

Copyright © 1997 Alex Chaffee

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

why reinvent the wheel? Use strong, static typing wherever possible Use multiple methods to express multiple

functionality

Page 24: JDBC

Copyright © 1997 Alex Chaffee

JDBC AncestryJDBC Ancestry

X/OPEN

ODBC JDBC

Page 25: JDBC

Copyright © 1997 Alex Chaffee

JDBC ArchitectureJDBC Architecture

Application 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

Page 26: JDBC

Copyright © 1997 Alex Chaffee

JDBC DriversJDBC Drivers

Type I: “Bridge” Type II: “Native” Type III: “Middleware” Type IV: “Pure”

Page 27: JDBC

Copyright © 1997 Alex Chaffee

JDBC Drivers (Fig.)JDBC Drivers (Fig.)

JDBC

Type I“Bridge”

Type II“Native”

Type III“Middleware”

Type IV“Pure”

ODBCODBCDriver

CLI (.lib)

MiddlewareServer

Page 28: JDBC

Copyright © 1997 Alex Chaffee

Type I DriversType I Drivers

Use bridging technology Requires installation/configuration on client

machines Not good for Web e.g. ODBC Bridge

Page 29: JDBC

Copyright © 1997 Alex Chaffee

Type II DriversType II Drivers

Native API drivers Requires installation/configuration on client

machines Used to leverage existing CLI libraries Usually not thread-safe Mostly obsolete now e.g. Intersolv Oracle Driver, WebLogic drivers

Page 30: JDBC

Copyright © 1997 Alex Chaffee

Type III DriversType III Drivers

Calls middleware server, usually on database host

Very flexible -- allows access to multiple databases using one driver

Only need to download one driver But it’s another server application to install

and maintain e.g. Symantec DBAnywhere

Page 31: JDBC

Copyright © 1997 Alex Chaffee

Type IV DriversType IV Drivers

100% Pure Java -- the Holy Grail Use 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

Page 32: JDBC

Copyright © 1997 Alex Chaffee

JDBC LimitationsJDBC Limitations

No scrolling cursors No bookmarks

Page 33: JDBC

Copyright © 1997 Alex Chaffee

Related TechnologiesRelated Technologies

ODBC Requires configuration (odbc.ini)

RDO, ADO Requires Win32

OODB e.g. ObjectStore from ODI

JavaBlend maps objects to tables transparently (more or less)

Page 34: JDBC

Copyright © 1997 Alex Chaffee

Part III: JDBC APIsPart III: JDBC APIs

Page 35: JDBC

Copyright © 1997 Alex Chaffee

java.sqljava.sql

JDBC is implemented via classes in the java.sql package

Page 36: JDBC

Copyright © 1997 Alex Chaffee

Loading a Driver DirectlyLoading a Driver Directly

Driver d = new foo.bar.MyDriver();

Connection c = d.connect(...); Not recommended, use DriverManager

instead Useful if you know you want a particular

driver

Page 37: JDBC

Copyright © 1997 Alex Chaffee

DriverManagerDriverManager

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!

Page 38: JDBC

Copyright © 1997 Alex Chaffee

Registering a DriverRegistering a Driver

statically load driverClass.forName(“foo.bar.MyDriver”);

Connection c = DriverManager.getConnection(...);

or use the jdbc.drivers system property

Page 39: JDBC

Copyright © 1997 Alex Chaffee

JDBC Object ClassesJDBC 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

Page 40: JDBC

Copyright © 1997 Alex Chaffee

JDBC Class UsageJDBC Class Usage

DriverManager

Driver

Connection

Statement

ResultSet

Page 41: JDBC

Copyright © 1997 Alex Chaffee

JDBC URLsJDBC URLs

jdbc:subprotocol:source each driver has its own subprotocol each subprotocol has its own syntax for the

sourcejdbc:odbc:DataSource

e.g. jdbc:odbc:Northwind

jdbc:msql://host[:port]/database e.g. jdbc:msql://foo.nowhere.com:4333/accounting

Page 42: JDBC

Copyright © 1997 Alex Chaffee

DriverManagerDriverManager

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

Page 43: JDBC

Copyright © 1997 Alex Chaffee

ConnectionConnection 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

NB: Some drivers don’t support serialized connections Fortunately, most do (now)

Also provides “metadata” -- information about the database, tables, and fields

Also methods to deal with transactions

Page 44: JDBC

Copyright © 1997 Alex Chaffee

Obtaining a ConnectionObtaining 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(); }

Page 45: JDBC

Copyright © 1997 Alex Chaffee

Connection MethodsConnection 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

Why all these different kinds of statements? Optimization.

Page 46: JDBC

Copyright © 1997 Alex Chaffee

StatementStatement

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

Page 47: JDBC

Copyright © 1997 Alex Chaffee

Statement MethodsStatement MethodsResultSet 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.

Why all these different kinds of queries? Optimization.

Page 48: JDBC

Copyright © 1997 Alex Chaffee

ResultSetResultSet 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.

you can’t rewind

Page 49: JDBC

Copyright © 1997 Alex Chaffee

ResultSet MethodsResultSet 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 allows you to re-use the Statement that created it automatically called by most Statement methods

Page 50: JDBC

Copyright © 1997 Alex Chaffee

ResultSet MethodsResultSet Methods Type getType(int columnIndex)

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

Type getType(String columnName) same, but uses name of field less efficient

int findColumn(String columnName) looks up column index given column name

Page 51: JDBC

Copyright © 1997 Alex Chaffee

ResultSet MethodsResultSet 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)

Page 52: JDBC

Copyright © 1997 Alex Chaffee

ResultSet MethodsResultSet 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)

Page 53: JDBC

Copyright © 1997 Alex Chaffee

isNullisNull

In SQL, NULL means the field is empty Not the same as 0 or “” In JDBC, you must explicitly ask if a field

is null by calling ResultSet.isNull(column)

Page 54: JDBC

Copyright © 1997 Alex Chaffee

Sample DatabaseSample Database

Employee ID Last Name First Name

1 Davolio Nancy

2 Fuller Andrew

3 Leverling Janet

4 Peacock Margaret

5 Buchanan Steven

Page 55: JDBC

Copyright © 1997 Alex Chaffee

SELECT ExampleSELECT Example

Connection con = DriverManager.getConnection(url, "alex", "8675309");

Statement st = con.createStatement();

ResultSet results = st.executeQuery("SELECT EmployeeID, LastName, FirstName FROM Employees");

Page 56: JDBC

Copyright © 1997 Alex Chaffee

SELECT Example (Cont.)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();

Page 57: JDBC

Copyright © 1997 Alex Chaffee

Mapping Java Types to SQL Mapping Java Types to SQL TypesTypes

SQL type Java TypeCHAR, VARCHAR, LONGVARCHAR StringNUMERIC, DECIMAL java.math.BigDecimalBIT booleanTINYINT byteSMALLINT shortINTEGER intBIGINT longREAL floatFLOAT, DOUBLE doubleBINARY, VARBINARY, LONGVARBINARY byte[]DATE java.sql.DateTIME java.sql.TimeTIMESTAMP java.sql.Timestamp

Page 58: JDBC

Copyright © 1997 Alex Chaffee

Database TimeDatabase Time

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

year, month, day

java.sql.Time hours, minutes, seconds

java.sql.Timestamp year, month, day, hours, minutes, seconds, nanoseconds usually use this one

Page 59: JDBC

Copyright © 1997 Alex Chaffee

Modifying the DatabaseModifying the Database

use executeUpdate if the SQL contains “INSERT” or “UPDATE”

Why isn’t it smart enough to parse the SQL? Optimization.

executeUpdate returns the number of rows modified

executeUpdate also used for “CREATE TABLE” etc. (DDL)

Page 60: JDBC

Copyright © 1997 Alex Chaffee

INSERT exampleINSERT example

Page 61: JDBC

Copyright © 1997 Alex Chaffee

Transaction ManagementTransaction 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

Page 62: JDBC

Copyright © 1997 Alex Chaffee

setAutoCommitsetAutoCommit

Connection.setAutoCommit(boolean) if AutoCommit is false, then every statement

is added to an ongoing transaction you must explicitly commit or rollback the

transaction using Connection.commit() and Connection.rollback()

Page 63: JDBC

Copyright © 1997 Alex Chaffee

Connection ManagersConnection Managers

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 CM’s pool

Why? Because opening and closing connections takes a long time

Warning: the CM should always setAutoCommit(false) when a connection is returned

Page 64: JDBC

Copyright © 1997 Alex Chaffee

Optimized StatementsOptimized 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()

Page 65: JDBC

Copyright © 1997 Alex Chaffee

JDBC Class DiagramJDBC Class Diagram

Whoa!

Page 66: JDBC

Copyright © 1997 Alex Chaffee

MetadataMetadata

Connection: DatabaseMetaData getMetaData()

ResultSet: ResultSetMetaData getMetaData()

Page 67: JDBC

Copyright © 1997 Alex Chaffee

ResultSetMetaDataResultSetMetaData 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...

Page 68: JDBC

Copyright © 1997 Alex Chaffee

DatabaseMetaDataDatabaseMetaData

What tables are available? What's our user name as known to the

database? Is the database in read-only mode? If table correlation names are supported, are

they restricted to be different from the names of the tables?

and so on…

Page 69: JDBC

Copyright © 1997 Alex Chaffee

JavaBlend: Java to Relational JavaBlend: Java to Relational MappingMapping

Page 70: JDBC

JDBC 2.0JDBC 2.0

Scrollable result set Batch updates Advanced data types

Blobs, objects, structured types

Rowsets Persistent JavaBeans

JNDI Connection Pooling Distributed transactions via JTS

Page 71: JDBC

Copyright © 1997 Alex Chaffee

SummarySummary

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

Page 72: JDBC

Copyright © 1997 Alex Chaffee

Where to get more informationWhere to get more information

Other training sessions 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/ (Author’s

site)


Recommended