Download - JDBC™ Fundamentals (a.k.a. Java Database Connectivity, although technically not an acronym) ©SoftMoore ConsultingSlide 1.

Transcript
Page 1: JDBC™ Fundamentals (a.k.a. Java Database Connectivity, although technically not an acronym) ©SoftMoore ConsultingSlide 1.

JDBC™ Fundamentals

(a.k.a. Java Database Connectivity,although technically not an acronym)

©SoftMoore Consulting Slide 1

Page 2: JDBC™ Fundamentals (a.k.a. Java Database Connectivity, although technically not an acronym) ©SoftMoore ConsultingSlide 1.

Basic Idea

• Use JDBC to connect to a relational database and perform standard SQL queries to read and write data

• Low-level Java interface for SQL commands based on ODBC

• Related Concepts:– SQL– ODBC

• Contained in two packages– java.sql– javax.sql

©SoftMoore Consulting Slide 2

Page 3: JDBC™ Fundamentals (a.k.a. Java Database Connectivity, although technically not an acronym) ©SoftMoore ConsultingSlide 1.

JDBC Advantages

• Allows a pure-Java connection to a database– All programming remains in Java domain, with full access to

Java features– Automatic conversion between SQL types and Java types

• Cross-platform and database independent– Code with any database for which there is a JDBC driver

• Can access virtually any data source– relational database– spreadsheet– text file

©SoftMoore Consulting Slide 3

Page 4: JDBC™ Fundamentals (a.k.a. Java Database Connectivity, although technically not an acronym) ©SoftMoore ConsultingSlide 1.

Objectives

• Use JDBC to connect to a relational database

• Execute SQL queries on the database

• Handle the results of a query

• View the structure of a database using metadata

• Understand JDBC exceptions and warnings

©SoftMoore Consulting Slide 4

Page 5: JDBC™ Fundamentals (a.k.a. Java Database Connectivity, although technically not an acronym) ©SoftMoore ConsultingSlide 1.

Alternatives/Related Technology

• Hibernate

• Java Data Objects (JDO)

• TopLink

• EJB3 Java Persistence API (JPA)

• Serialization

©SoftMoore Consulting Slide 5

Page 6: JDBC™ Fundamentals (a.k.a. Java Database Connectivity, although technically not an acronym) ©SoftMoore ConsultingSlide 1.

Using JDBC

©SoftMoore Consulting Slide 6

JDBC/ODBCBridge

ODBCDriver

Vendor-supplied

JDBC Driver

Database Database

JDBC API

JDBC Driver API

Java Applicationusing JDBC

JDBC Driver Manager

Page 7: JDBC™ Fundamentals (a.k.a. Java Database Connectivity, although technically not an acronym) ©SoftMoore ConsultingSlide 1.

JDBC Driver Types

• Type 1: JDBC-ODBC Bridge plus ODBC– relies on a local ODBC driver to access database – Oracle provides a JDBC-ODBC bridge – not usually suitable for production use

• Type 2: Native-API Partly-Java– converts JDBC calls to native database API calls of local driver– requires that some platform-specific binary code be loaded on

each client machine

©SoftMoore Consulting Slide 7

Page 8: JDBC™ Fundamentals (a.k.a. Java Database Connectivity, although technically not an acronym) ©SoftMoore ConsultingSlide 1.

JDBC Driver Types(continued)

• Type 3: JDBC-Net Pure Java– translates JDBC calls to database-neutral protocol to

communicate with a Java application server– server converts requests to connect its pure Java clients to

many different databases– most flexible alternative

• Type 4: Native-Protocol Pure Java– converts JDBC calls directly into database-specific protocol

©SoftMoore Consulting Slide 8

Page 9: JDBC™ Fundamentals (a.k.a. Java Database Connectivity, although technically not an acronym) ©SoftMoore ConsultingSlide 1.

Vendor Support

• Most database vendors supply type 3 and type 4 drivers.

• List of companies supporting JDBChttp://www.oracle.com/technetwork/java/index-136695.html

• List of available JDBC drivershttp://www.devx.com/tips/Tip/28818

http://www.roseindia.net/tutorial/java/jdbc/listofjdbcdriver.html

©SoftMoore Consulting Slide 9

Page 10: JDBC™ Fundamentals (a.k.a. Java Database Connectivity, although technically not an acronym) ©SoftMoore ConsultingSlide 1.

ODBC Data Sources

• Databases accessed through ODBC are called data sources.

• Various kinds of ODBC data sources – relational databases– spreadsheets – text files

• Each ODBC data source must have an ODBC driver.

• The ODBC driver for the data source acts as a server to handle requests from ODBC clients.

©SoftMoore Consulting Slide 10

Page 11: JDBC™ Fundamentals (a.k.a. Java Database Connectivity, although technically not an acronym) ©SoftMoore ConsultingSlide 1.

Creating a Data Source in Windows

The ODBC Data Source Dialog

©SoftMoore Consulting Slide 11

Page 12: JDBC™ Fundamentals (a.k.a. Java Database Connectivity, although technically not an acronym) ©SoftMoore ConsultingSlide 1.

SQL Conformance

• Databases differ on how they implement advanced SQL features.

• JDBC allows any string to be passed to driver, allowing access to non-standard advanced features .

• JDBC drivers and ODBC drivers accessed through the JDBC-ODBC bridge may have different conformance levels.

©SoftMoore Consulting Slide 12

Page 13: JDBC™ Fundamentals (a.k.a. Java Database Connectivity, although technically not an acronym) ©SoftMoore ConsultingSlide 1.

SQL Conformance: JDBC Drivers

• Not all JDBC drivers support latest ANSI SQL grammar .

• All JDBC-compliant drivers support Entry Level SQL.

• Use DatabaseMetaData object methods to determine conformance level: – supportsANSI92EntryLevelSQL() – supportsANSI92IntermediateSQL() – supportsANSI92FullSQL()

©SoftMoore Consulting Slide 13

Page 14: JDBC™ Fundamentals (a.k.a. Java Database Connectivity, although technically not an acronym) ©SoftMoore ConsultingSlide 1.

Using JDBC with Applets

• Problem: How to allow applets to access databases

• Issues: – Distribution (want to avoid binaries) – Security

• Solution: use three-tier approach:

• Applet ↔ server ↔ database– applet uses a socket connection to the web host to send

database requests to an intermediate server – server receives the request and spawns a thread to handle the

database connection – server returns the results to the applet

©SoftMoore Consulting Slide 14

Page 15: JDBC™ Fundamentals (a.k.a. Java Database Connectivity, although technically not an acronym) ©SoftMoore ConsultingSlide 1.

Basic Steps in Using JDBC

• Load a JDBC driver

• Connect to the data source

• Execute SQL statements

• Process query results

• Commit or rollback database changes

• Close the connection

©SoftMoore Consulting Slide 15

Page 16: JDBC™ Fundamentals (a.k.a. Java Database Connectivity, although technically not an acronym) ©SoftMoore ConsultingSlide 1.

©SoftMoore Consulting

The JDBC Driver Manager

• Management layer of JDBC

• When a Driver class is loaded, it registers itself with the DriverManager.

• The DriverManager maintains list of all drivers that have registered.

• Multiple drivers can be loaded/registered. The DriverManager automatically determines which driverto use for a connection.

Slide 16

Page 17: JDBC™ Fundamentals (a.k.a. Java Database Connectivity, although technically not an acronym) ©SoftMoore ConsultingSlide 1.

Loading a Driver

• Using method Class.forName()String driverName = "oracle.jdbc.driver.OracleDriver";Class.forName(driverName);

• From the property jdbc.drivers– from the command-line

java -Djdbc.drivers=oracle.jdbc.driver.OracleDriver JavaProgram

– from within the applicationSystem.setProperty("jdbc.drivers", "oracle.jdbc.driver.OracleDriver");

• By creating an instance with a constructor– (not recommended)

new oracle.jdbc.driver.OracleDriver();

©SoftMoore Consulting Slide 17

Page 18: JDBC™ Fundamentals (a.k.a. Java Database Connectivity, although technically not an acronym) ©SoftMoore ConsultingSlide 1.

DriverManager.setLogWriter()

• The PrintWriter where the driver manager sends trace messages.

• By default, the PrintWriter used for logging is set to null (disabled).

• To watch log messages use PrintWriter pw = new PrintWriter(System.out); DriverManager.setLogWriter(pw);

©SoftMoore Consulting Slide 18

Page 19: JDBC™ Fundamentals (a.k.a. Java Database Connectivity, although technically not an acronym) ©SoftMoore ConsultingSlide 1.

Connecting

Uses a JDBC URL of the form jdbc:<subprotocol>:<sourceName>

where

• jdbc is the protocol

• <subprotocol> is the name of the driver or the database connectivity mechanism

• <sourceName> is a driver-specific name that identifies the data source (database)

©SoftMoore Consulting Slide 19

Page 20: JDBC™ Fundamentals (a.k.a. Java Database Connectivity, although technically not an acronym) ©SoftMoore ConsultingSlide 1.

Example: Making a Connection

String url = "jdbc:derby:Accounts";String user = "dba";String pw = "Hello";

Connection conn = DriverManager.getConnection(url, user, pw);

©SoftMoore Consulting Slide 20

Note: getConnection() throws aSQLException on failure to connect.

Page 21: JDBC™ Fundamentals (a.k.a. Java Database Connectivity, although technically not an acronym) ©SoftMoore ConsultingSlide 1.

©SoftMoore Consulting

JDBC Statements

• Method DriverManager.getConnection() returns a Connection object.

• Use Connection.createStatement() to create Statement objects.

• Use Statement objects to execute SQL commands.

• Results of a query will held in ResultSet objects.

Slide 21

Page 22: JDBC™ Fundamentals (a.k.a. Java Database Connectivity, although technically not an acronym) ©SoftMoore ConsultingSlide 1.

Three Kinds of JDBC Statements

©SoftMoore Consulting Slide 22

«interface»Statement

«interface»CallableStatement

«interface»PreparedStatement

Simple SQL statement with no parameters

Precompiled SQL statement (may have input parameters)

Used to execute database stored procedures

Page 23: JDBC™ Fundamentals (a.k.a. Java Database Connectivity, although technically not an acronym) ©SoftMoore ConsultingSlide 1.

Statement Execute Methods

• JDBC statements send SQL commands by using one of three execute methods defined in the Statement interface.

• The method to use depends on the result of the statement:– executeQuery() is used for SELECT– executeUpdate() is used for INSERT, UPDATE, DELETE,

CREATE TABLE, etc.– execute() is used rarely for very special cases

©SoftMoore Consulting Slide 23

Page 24: JDBC™ Fundamentals (a.k.a. Java Database Connectivity, although technically not an acronym) ©SoftMoore ConsultingSlide 1.

Statement.executeQuery()

• Used when there will be one ResultSet

• Represents a table of results

• The SQL query is passed as a String argument.

©SoftMoore Consulting Slide 24

Page 25: JDBC™ Fundamentals (a.k.a. Java Database Connectivity, although technically not an acronym) ©SoftMoore ConsultingSlide 1.

ResultSet

• Maintains a row cursor for iterating forward through the rows of the result table

• Initial position of cursor is before the first row

• The next() method– moves the cursor to the next row of the result table– returns true while there are more rows in the result

©SoftMoore Consulting Slide 25

Page 26: JDBC™ Fundamentals (a.k.a. Java Database Connectivity, although technically not an acronym) ©SoftMoore ConsultingSlide 1.

Example: Book Schema

©SoftMoore Consulting Slide 26

publisher_id name url

publisher

book_id title isbn publisher_id

book

book_id author_id seq_num

book_author

author_id last_name first_name

author

Page 27: JDBC™ Fundamentals (a.k.a. Java Database Connectivity, although technically not an acronym) ©SoftMoore ConsultingSlide 1.

Executing a Query

String query = "select * from book order by title";

Connection conn = DriverManager.getConnection(url, user, pw);

Statement stmt = conn.createStatement();ResultSet rs = stmt.executeQuery(query);

while (rs.next()) { ... }

©SoftMoore Consulting Slide 27

Page 28: JDBC™ Fundamentals (a.k.a. Java Database Connectivity, although technically not an acronym) ©SoftMoore ConsultingSlide 1.

GetXXX() Methods

• The ResultSet objects have getXXX() methods to get the values of each column in a row of data

• Different getXXX() method for each supported data type; e.g., getInt(), getString(), ...

• Can refer to columns by name or number Warning: first column has number 1, not 0!

©SoftMoore Consulting Slide 28

Page 29: JDBC™ Fundamentals (a.k.a. Java Database Connectivity, although technically not an acronym) ©SoftMoore ConsultingSlide 1.

Examples: GetXXX() Methods

int bookId = rs.getInt("book_id");

int bookId = rs.getInt(1); // same as above

String title = rs.getString("title");

String isbn = rs.getString("isbn");

©SoftMoore Consulting Slide 29

Page 30: JDBC™ Fundamentals (a.k.a. Java Database Connectivity, although technically not an acronym) ©SoftMoore ConsultingSlide 1.

Java-SQL Type Equivalence

©SoftMoore Consulting Slide 30

Java Method SQL Type

boolean getBoolean() BIT

short getShort() SMALLINT

int getInt() INTEGER

long getLong() BIGINT

float getFloat() REAL

double getDouble()FLOAT

DOUBLE

Page 31: JDBC™ Fundamentals (a.k.a. Java Database Connectivity, although technically not an acronym) ©SoftMoore ConsultingSlide 1.

Java-SQL Type Equivalence(continued)

©SoftMoore Consulting Slide 31

Java Method SQL Type

BigDecimal getBigDecimal()

NUMERIC

DECIMAL

String getString()CHAR

VARCHAR

byte[] getBytes()BINARY

VARBINARY

Object getObject() any type

Page 32: JDBC™ Fundamentals (a.k.a. Java Database Connectivity, although technically not an acronym) ©SoftMoore ConsultingSlide 1.

Java-SQL Type Equivalence(continued)

©SoftMoore Consulting Slide 32

Java Method SQL Type

Clob getClob() CLOB

Blob getBlob() BLOB

Date getDate() DATE

Time getTime() TIME

Timestamp getTimeStamp() TIMESTAMP

Classes Blob, Clob, Date, Time, and Timestampare defined in package java.sql.

Page 33: JDBC™ Fundamentals (a.k.a. Java Database Connectivity, although technically not an acronym) ©SoftMoore ConsultingSlide 1.

Java Strings and SQL CHARS

• SQL types CHAR, VARCHAR, and LONGVARCHAR all map to Java strings.

• Fixed-length SQL strings (CHAR(n)) are padded to length n during conversion to Java strings.

• The same padding occurs when converting Java strings to SQL fixed-length strings.

©SoftMoore Consulting Slide 33

Page 34: JDBC™ Fundamentals (a.k.a. Java Database Connectivity, although technically not an acronym) ©SoftMoore ConsultingSlide 1.

Getting LONGVARCHAR as Java Streams

• When retrieving large strings of type LONGVARCHAR, the ResultSet methods– getAsciiStream() and– getUnicodeStream()

can be used to get the value as a stream.

©SoftMoore Consulting Slide 34

Page 35: JDBC™ Fundamentals (a.k.a. Java Database Connectivity, although technically not an acronym) ©SoftMoore ConsultingSlide 1.

Binary SQL Values

• As with SQL strings, SQL binary types, BINARY, VARBINARY, and LONGVARBINARY are all mapped to Java byte[] objects

• The ResultSet method getBinaryStream() can be used to read large binary objects (LONGVARBINARY)

©SoftMoore Consulting Slide 35

Page 36: JDBC™ Fundamentals (a.k.a. Java Database Connectivity, although technically not an acronym) ©SoftMoore ConsultingSlide 1.

Example: List Books byJames Rumbaugh

String query = "select b.title" + " from book b, book_author ba, author a" + " where b.book_id = ba.book_id" + " and ba.author_id = a.author_id" + " and a.first_name = 'James'" + " and a.last_name = 'Rumbaugh'" + " order by title";

ConnectionFactory factory = ConnectionFactory.getInstance();Connection conn = factory.getConnection();Statement stmt = conn.createStatement();ResultSet rs = stmt.executeQuery(query);

System.out.println("Books by James Rumbaugh");while (rs.next()) System.out.println("- " + rs.getString("title"));

©SoftMoore Consulting Slide 36

Page 37: JDBC™ Fundamentals (a.k.a. Java Database Connectivity, although technically not an acronym) ©SoftMoore ConsultingSlide 1.

Statement.executeUpdate()

• Used for INSERT, UPDATE, or DELETE statements

• Also used for SQL data definition statements like CREATE TABLE and ALTER TABLE

• Return value is number of rows modified(there is no ResultSet object)

©SoftMoore Consulting Slide 37

Page 38: JDBC™ Fundamentals (a.k.a. Java Database Connectivity, although technically not an acronym) ©SoftMoore ConsultingSlide 1.

Example: Inserting Data

static String[] sqlInserts = { "insert into author values (1000, 'Gamma', 'Erich')", "insert into author values (1001, 'Helm', 'Richard')", "insert into author values (1002, 'Johnson', 'Ralph')", ... }

int updateCount = 0;

for (int i = 0; i < sqlInserts.length; ++i) updateCount += stmt.executeUpdate(sqlInserts[i]);

©SoftMoore Consulting Slide 38

Page 39: JDBC™ Fundamentals (a.k.a. Java Database Connectivity, although technically not an acronym) ©SoftMoore ConsultingSlide 1.

Additional Update Examples

// create table with name and height columnsstmt.executeUpdate("create table Data " + "(name varchar(30), height integer)");

// inserting datastmt.executeUpdate("insert into Data " + "values ('John', 68)");

// updating datastmt.executeUpdate("update Data" + " set height = 70" + " where name = 'John'");

// deleting datastmt.executeUpdate("delete from Data" + " where name = 'John'");

©SoftMoore Consulting Slide 39

Page 40: JDBC™ Fundamentals (a.k.a. Java Database Connectivity, although technically not an acronym) ©SoftMoore ConsultingSlide 1.

Statement.execute()

• Used for cases when the statement might– return more than one ResultSet– return more than one update count

(number of rows modified)– return a combination of both

• Can always be used if programmer is unsure of the result

• Example: A stored procedure may execute multiple statements, each of which will have a result.

©SoftMoore Consulting Slide 40

Page 41: JDBC™ Fundamentals (a.k.a. Java Database Connectivity, although technically not an acronym) ©SoftMoore ConsultingSlide 1.

Retrieving Results FromStatement.execute()

• Method Statement.execute() returns a boolean – true if next result is a ResultSet – false if next result is an update count– false if there are no more results

• Use Statement.getResultSet() to get the current result as a ResultSet object

• Use Statement.getMoreResults() to move to the next result

• Use Statement.getUpdateCount() to get the current result as an update count

©SoftMoore Consulting Slide 41

Page 42: JDBC™ Fundamentals (a.k.a. Java Database Connectivity, although technically not an acronym) ©SoftMoore ConsultingSlide 1.

Multiple Result Sets In Practice

• Not common

• Used primarily when the programmer usually knows what to expect, either from database or stored procedure documentation

• Might not be supported by the database.

©SoftMoore Consulting Slide 42

Page 43: JDBC™ Fundamentals (a.k.a. Java Database Connectivity, although technically not an acronym) ©SoftMoore ConsultingSlide 1.

Closing the Connection

• Ensures that system resources are freedconn.close();

• Can also close– Statement objects

• closed automatically when the connection is closed– ResultSet objects

• closed automatically when the statement is closed

©SoftMoore Consulting Slide 43