SDSU CS 596: Client-Server Programming
Spring Semester, 1997
Doc 30, JDBC

To Lecture Notes Index
San Diego State University -- This page last updated May 1, 1997

Contents of Doc 30, JDBC

Databases
SQL and Java slide # 1
...JDBC slide # 2
...JDBC Architecture slide # 2
...Using JDBC slide # 4
......Outline slide # 4
......Loading a Driver slide # 4
......Connecting to a Database slide # 6
......Issue Queries and Receive Results slide # 8
......ResultSet - Result of a Query slide # 10
......SQL Data Types and Java slide # 11
......Statement Methods slide # 12
......Connection Methods slide # 12
......Transactions slide # 13
......PreparedStatement slide # 15
......CallableStatement slide # 17
......DatabaseMetaData slide # 17

References

http://www.sdsu.edu/doc/java-1.1.1/doc/guide/jdbc/index.html, Sun's on-line JDBC Tutorial/Documentation

Client/Server Programming with Java and CORBA, Orfali and Harkey, John Wiley and Sons, Inc. 1997


Doc 30, JDBC Slide # 1

SQL and Java

Some Jargon

SQL Access Group (SAG) - multivendor "Standards" group

SQL Call Level Interface (CLI) is the SAG standard for connecting remotely to a database from a program

CLI uses a driver which connects to the database

Program uses a driver manager to talk to the driver

The driver is database specific

In 1994 X/Open adopted SQL CLI to produce X/Open CLI

In 1996 X/Open CLI was adapted by ISO to become ISO 9075-3 Call level Interface


Microsoft's Open Database Connectivity (ODBC) is an extensions of the SAG CLI

ODBC 2.0 (32 bit) has three conformance levels

Core - 23 API calls to perform basic SQL stuff

Level 1 - 19 calls relating to large object (BLOBs) and driver-specific

Level 2 - 19 API calls supporting scrolling (cursors)


Doc 30, JDBC Slide # 2

JDBC

Java Database Connectivity

Sun states that JDBC is a trademark and not an abbreviation for Java Database Connectivity

Sun also states that some people think JDBC is an abbreviation for Java Database Connectivity

JDBC is a portable SQL CLI written in Java.

Like all CLIs, JDBC does not replace or extend SQL, it just allows your program to make SQL calls to a database

Most references claim JDBC is easier to use/understand than ODBC

JDBC Architecture




Doc 30, JDBC Slide # 3
JDBC Classes
java.sql package

InterfacesClasses
CallableStatement Date
Connection DriverManager
DatabaseMetaData DriverPropertyInfo
Driver Time
PreparedStatement Timestamp
ResultSet Types
ResultSetMetaData
Statement

Exceptions

DataTruncation
SQLException
SQLWarning

Doc 30, JDBC Slide # 4

Using JDBC

Outline


Step 1.Load the driver(s)

Step 2.Connect to the database

Step 3.Issue queries and receive results


Loading a Driver


A well written JDBC driver is loaded using Class.forName

To load the Oracle driver

import java.sql.*; 

class JdbcTest
{ 
   public static void main (String args [])  throws
                        ClassNotFoundException
   { 
      Class.forName ("oracle.jdbc.OracleDriver");
   }
}

This requires that oracle package be in your path

A properly written driver will register itself with the DriverManager class


Doc 30, JDBC Slide # 5
java.sql.DriverManager

Driver related methods
deregisterDriver(Driver)
getDriver(String)
getDrivers()
registerDriver(Driver)

Connecting to a database
getConnection(String, Properties)
getConnection(String, String, String)
getConnection(String)

getLoginTimeout()
setLoginTimeout(int)

Logging/tracing/Debugging
getLogStream()
setLogStream(PrintStream)
println(String)
Print a message to the current JDBC log stream


Doc 30, JDBC Slide # 6

Connecting to a Database

import java.sql.*; 

class JdbcTest
{ 
   static String ARS_URL = "jdbc:oracle:@PutDatabaseNameHere";

   public static void main (String args [])  throws 
         SQLException, ClassNotFoundException
   { 
      Class.forName ("oracle.jdbc.OracleDriver");
      Connection ARS;
      ARS =DriverManager.getConnection(ARS_URL, 
                        "whitney", 
                        "secret");
   } 
} 

JDBC URL Structure

jdbc:<subprotocol>:<subname>

<subprotocol> is usually the driver or database connectivity mechanism

<subname> depends on the <subprotocol>, can vary with vender

<subname> can include Internet address for remote databases


Doc 30, JDBC Slide # 7
Forms of getConnection
(With Oracle's <
subname>)

getConnection(URL, Properties)
getConnection(URL, userName, Password)
getConnection(URLWithUsernamePassword)

Three equivalent getConnection's

static String ARS_URL = "jdbc:oracle:@PutDatabaseNameHere";

DriverManager.getConnection(ARS_URL, "whitney","secret");

DriverManager.getConnection(
   "jdbc:oracle:whitney/secret@PutDatabaseNameHere");

java.util.Properties info = new java.util.Properties();
info.addProperty ("user", "whitney");
info.addProperty ("password","secret");

DriverManager getConnection (ARS_URL ,info );

Doc 30, JDBC Slide # 8

Issue Queries and Receive Results

Example

import java.sql.*; 
import java.io.*; 

class JdbcTest
{ 
   static String ARS_URL = "jdbc:oracle:@PutDatabaseNameHere";

   public static void main (String args [])  throws 
         SQLException, ClassNotFoundException, IOException
   { 
      Class.forName ("oracle.jdbc.OracleDriver");
      Connection ARS;
      ARS =DriverManager.getConnection(ARS_URL, 
                        "whitney", "secret");

      Statement schedule = ARS.createStatement (); 

      String flightOut =    "SELECT * FROM AirlineSchedule 
                        WHERE from = SAN";

      ResultSet fromSanDiego = schedule.executeQuery (flightOut);
      while ( fromSanDiego.next() ) 
      { 
         System.out.println (fromSanDiego.getString ("to")); 
      } 
   } 
} 


Doc 30, JDBC Slide # 9
AirlineScehdule table
(As if you don't remember it)

AirlineSchedule
FromToDepart TimeArrival TimeFlight numberAircraft type
AMSLAX04:1515:15602C
DEDFW9:0011:301201B
DEDFW12:0014:301202B
DEDFW16:0018:301203B
DEFAR10:1212:12902A
etc.


Doc 30, JDBC Slide # 10

ResultSet - Result of a Query


JDBC returns a ResultSet as a result of a query

A ResultSet contains all the rows and columns that satisfy the SQL statement

A cursor is maintained to the current row of the data

The cursor is valid until the ResultSet object or its Statement object are closed

next() method advances the cursor to the next row

You can access columns of the current row by index or name

ResultSet has getXXX methods that:

have either a column name or column index as argument

return the data in that column converted to type XXX

getAsciiStream(int)getDate(int)getObject(int)
getBigDecimal(int,int)getDouble(int)getShort(int)
getBinaryStream(int)getFloat(int)getString(int)
getBoolean(int)getInt(int)getTime(int)
getByte(int)getLong(int)getTimestamp(int)
getBytes(int)getMetaData()getUnicodeStream(int)

clearWarnings() getCursorName()wasNull()
close() getWarnings()
findColumn(String)next()

Doc 30, JDBC Slide # 11

SQL Data Types and Java


SQL typeJava type
CHARString
VARCHARString
LONGVARCHARString
NUMERICjava.math.BigDecimal
DECIMALjava.math.BigDecimal
BITboolean
TINYINTbyte
SMALLINTshort
INTEGERint
BIGINTlong
REALfloat
FLOATdouble
DOUBLEdouble
BINARYbyte[]
VARBINARYbyte[]
LONGVARBINARYbyte[]
DATEjava.sql.Date
TIMEjava.sql.Time
TIMESTAMPjava.sql.Timestamp


Doc 30, JDBC Slide # 12

Statement Methods


cancel() getQueryTimeout()
clearWarnings() getResultSet()
close() getUpdateCount()
execute(String) getWarnings()
executeQuery(String) setCursorName(String)
executeUpdate(String) setEscapeProcessing(boolean)
getMaxFieldSize() setMaxFieldSize(int)
getMaxRows() setMaxRows(int)
getMoreResults() setQueryTimeout(int)

Connection Methods

clearWarnings() isReadOnly()
close() nativeSQL(String)
commit() prepareCall(String)
createStatement() prepareStatement(String)
getAutoCommit() rollback()
getCatalog() setAutoCommit(boolean)
getMetaData() setCatalog(String)
getTransactionIsolation() setReadOnly(boolean)
getWarnings() setTransactionIsolation(int)
isClosed()


Doc 30, JDBC Slide # 13

Transactions


A transaction consists of one or more statements that have been executed and completed

A transaction ends when a commit or rollback is sent

Connections are opened in auto commit mode:

when a statement is completed, it is committed

Transactions and Concurrency

What happens to data that is changed in a transaction, but not yet committed?

Can other programs access the old or new values?

Use setTransactionIsolation(int) in Connection class to set access levels

Access levels are given as static fields of Connection class

TRANSACTION_NONE
TRANSACTION_READ_COMMITTED
TRANSACTION_READ_UNCOMMITTED
TRANSACTION_REPEATABLE_READ
TRANSACTION_SERIALIZABLE


Doc 30, JDBC Slide # 14
Transaction Example

import java.sql.*; 
import java.io.*; 

class JdbcTest
{ 
   static String ARS_URL = "jdbc:oracle:@PutDatabaseNameHere";

   public static void main (String args [])  throws 
         SQLException, ClassNotFoundException, IOException
   { 
      Class.forName ("oracle.jdbc.OracleDriver");
      Connection ARS;
      ARS =DriverManager.getConnection(ARS_URL, 
                        "whitney", "secret");

      ARS.setAutoCommit(false);

     String floodProblem = DELETE FROM AirlineSchedule WHERE
                                         from = 'FAR';

      String newflight =   INSERT INTO AirlineSchedule VALUES 
                               ( 'DE', 'SAN', '8:00', '12:00', '909', 'A');

      Statement schedule = ARS.createStatement (); 

      schedule.executeUpdate (floodProblem);
      schedule.executeUpdate (newflight);

      ARS.commit();
      ARS.close();
  } 
}

Doc 30, JDBC Slide # 15

PreparedStatement


PreparedStatement objects contain SQL statements that have been sent to the database to be prepared for execution

The SQL statements contains variables (IN parameters) which are given values before statement is executed

Only makes sense to use if database and driver keeps statements open after they have been committed

IN parameters are indicated by a ?

Values are set by position

String flightOut =    "SELECT * FROM AirlineSchedule 
                    WHERE from = ?";


Doc 30, JDBC Slide # 16
PreparedStatement Example

import java.sql.*; 
import java.io.*; 

class JdbcTest
{ 
   static String ARS_URL = "jdbc:oracle:@PutDatabaseNameHere";

   public static void main (String args [])  throws 
         SQLException, ClassNotFoundException, IOException
   { 
      Class.forName ("oracle.jdbc.OracleDriver");
      Connection ARS;
      ARS =DriverManager.getConnection(ARS_URL, 
                        "whitney", "secret");

      String flightOut =    "SELECT * FROM AirlineSchedule 
                        WHERE from = ?";

      PreparedStatement schedule;
      schedule = ARS.preparedStatement (flightOut); 

      schedule.setObject( 1, "SAN" );
      ResultSet fromSanDiego = schedule.executeQuery ();

      schedule. clearParameters();
      schedule.setObject( 1, "LAX" );
      ResultSet fromLA = schedule.executeQuery ();

   } 
} 


Doc 30, JDBC Slide # 17

CallableStatement

Some databases have stored procedures (a procedure of SQL statements)

CallableStatement allows a Java program to invoke a stored procedure in a database



DatabaseMetaData


The class DatabaseMetaData allows you to obtain information about the database

The 113 methods in DatabaseMetaData gives you more information than you thought possible