0% found this document useful (0 votes)
25 views

Java Database Connection: Helia / Martti Laiho, 1998-2000

JDBC provides a standard interface for connecting to and querying databases in Java. It defines interfaces and classes for establishing a connection with a database, executing queries, processing result sets, and handling exceptions. The document discusses the JDBC API, driver types, data type mappings, common SQL and JDBC methods, transactions, and exception handling.

Uploaded by

krishnakapa
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views

Java Database Connection: Helia / Martti Laiho, 1998-2000

JDBC provides a standard interface for connecting to and querying databases in Java. It defines interfaces and classes for establishing a connection with a database, executing queries, processing result sets, and handling exceptions. The document discusses the JDBC API, driver types, data type mappings, common SQL and JDBC methods, transactions, and exception handling.

Uploaded by

krishnakapa
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 21

JDBC

Java Database Connection

Helia / Martti Laiho, 1998-2000


Notes on JDBC - Java Database Connection

Class Library: java.sql.*

Literature/sources:

• SunSoft: http://java.sun.com/products/jdbc JDBC Specification


• jdk1.3/docs/guide/jdbc/ JDBC Guide: Getting Started
• Seth White & al: JDBCTM API Tutorial and Reference, 2nd ed

• Horstmann & Cornell: Core JAVA Volume II Chapter 4


• Orfali & Harkey: Client/Server Programming with JAVA and CORBA
• Siple: The Complete Guide to JAVA Database Programming, McGraw-Hill

• SOLID JDBC: sj23win.zip SOLID JDBC Driver Programmer’s Guide

• Melton & Eisenberg: Understanding SQL and Java Together

Helia / Martti Laiho, 1998-2000


JDBC 1.0 API

• Designed by JavaSoft
• based on ISO SQL/CLI and Microsoft ODBC API
• provided in java.sql package
• 4 types of JDBC Driver implementation

Helia / Martti Laiho, 1998-2000


Types of JDBC Implementations
- Melton & Eisenberg

Type 1 Type 2 Type 3 Type 4

Java appl Java appl Java appl Java appl

JDBC-ODBC JDBC JDBC JDBC


bridge driver driver driver

ODBC Native DBMS- independent DBMS- specific


driver db-library protocol protocol

Proprietary Proprietary JDBC server


protocol protocol gateway

DBMS DBMS DBMS DBMS

- Oracle JDBC/OCI - Oracle Thin JDBC


- Sybase jConnect
- Solid

Helia / Martti Laiho, 1998-2000


SQL and Java data types

SQL data type: Java data type:

INT[EGER] int
SMALLINT short
NUMERIC (m, n) java.sql.BigDecimal
DECIMAL (m, n) java.sql.BigDecimal
DEC (m, n) java.sql.BigDecimal
FLOAT (n) double
REAL float
DOUBLE double
CHAR[ACTER] (n) String
VARCHAR (n) String
DATE java.sql.Date
TIME java.sql.Time
TIMESTAMP java.sql.Timestamp

Helia / Martti Laiho, 1998-2000


Java.sql - Interfaces / Methods
DatabaseMetaData

Driver getTables(…)

...

Connection Statement ResultSet ResultSetMetaData

getMetaData() setCursorName(s) getColumnCount()


DriverManager setAutoCommit(b) executeQuery(sql) getMetaData() getColumnName(i)
Class setTransaction executeUpdate(sql) findColumn(name) getColumnLabel(i)
Isolation(level) cancel() next() getColumnDisplaySize(i)
createStatement() close() getInt(col)
getConnection getShort(col)
prepareStatement(sql)
(url, user, psw) getNumeric(col)
prepareCall(sql)
PreparedStatement getDouble(col)
commit()
rollback() getFloat(col)
close() … getString(col)
setXxxx(n, hvar) getDate(col)
clearParameters() getTime(col)
getTimestamp(col)
wasNull()
setText(s)
SQLException CallableStatement
append(s)
close()
getSQLState() registerOutputParameter
getErrorCode() execute()
getNextExcetion() ...

Helia / Martti Laiho, 1998-2000


SQL Query
String s;
float n;
...
String query = "SELECT COF_NAME, PRICE FROM COFFEES";
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
s = rs.getString("COF_NAME"); rs.next() COF_NAME PRICE
n = rs.getFloat("PRICE");
System.out.println(s + " " + n);
}
rs.close; rs.getString()

s rs.getFloat()
n

Helia / Martti Laiho, 1998-2000


SQLQuery Sequence Diagram
adapted from Orfali & Harkey
Client DriverManager

getConnection
Connection

createStatement
Statement
executeQuery
ResultSet

next

getString

getInt

...
{ [ Until next returns false ] }
close

close

close

Helia / Martti Laiho, 1998-2000


Invoking a Stored Procedure
adapted from Orfali & Harkey
Client DriverManager

getConnection
Connection

prepareCall
Callable
Statement
registerOutputParameter
parameters marked in the
... procedures call by ? placeholders
are identified by the corresponding
execute order numbers 1, 2, .. of the
placeholders

getString

getInt
...

close

close

Helia / Martti Laiho, 1998-2000


JDBC Escape Syntax

call {call proc (arg1, …) }


?=call {?= call proc (arg1, …) }
d {d ‘yyyy-mm-dd’}
escape {escape ‘%’}
fn {fn function (arg1, …) }
oj {oj outer-join }
t {t ‘hh:mm:ss’}
ts {ts ‘yyyy-mm-dd hh:mm:ss.fffff’}

Helia / Martti Laiho, 1998-2000


Transactions

Default: AutoCommit

Isolation Levels:
0 TRANSACTION_NONE
1 TRANSACTION_READ_UNCOMMITTED
2 TRANSACTION_READ_COMMITTED
3 TRANSACTION_REAPEATABLE_READ
4 TRANSACTION_SERIALIZABLE

Methods:
con.setAutoCommit(false);
level = con.getTransactionIsolation();
con.setTransactionIsolation(level);

con.commit();
con.rollback();

Helia / Martti Laiho, 1998-2000


Exception handling
- adapted from Core JAVA Vol II ch 4 p 206

try {
jdbc method call ...
}
catch (SQLException ex) {
System.out.println (”\nSQLException:");
while (ex != null) {
System.out.println (”SQLState: "+ex.getSQLState());
System.out.println (”Message: "+ ex.getMessage());
System.out.println (”Vendor: "+ ex.getErrorCode());
ex = ex.getNextException();
}
}
catch (java.lang.Exception ex) {
System.out.println("Exception: " + ex);
ex.printStackTrace ();
}
Helia / Martti Laiho, 1998-2000
JDBC 2.0 API
• JDBC 2.0 Core API (java.sql)
– Scrollable ResultSet
– Updating by ResultSet
– Batch Updates
– New SQL-99 datatypes

• JDBC 2.0 Standard Extension API (javax.sql)

Helia / Martti Laiho, 1998-2000


Scrollable ResultSet

• Resultset types
– TYPE_FORWARD_ONLY (~JDBC 1.0)
– TYPE_SCROLL_INSENSITIVE
– TYPE_SCROLL_SENSITIVE

• Methods
– beforeFirst() (initially)
– first()
– next() (JDBC 1.0)
– previous()
– last()
– afterLast()
– absolute (n | -n)
– relative (n | -n)
– getRow()
– isFirst() , isLast() , isBeforeFirst() , isAfterLast()
– moveToInsertRow(), moveToCurrentRow()

Helia / Martti Laiho, 1998-2000


Updatable ResultSet

• Updatable
– CONCUR_READ_ONLY (~JDBC 1.0)
– CONCUR_UPDATABLE

• Methods
– updateXXX(column, value)
– …
– updateRow() or cancelRowUpdates()

Helia / Martti Laiho, 1998-2000


Inserting a new row

• InsertRow processing: ResultSet:


– moveToInsertRow()
– updateXXX( , ) ….
– insertRow()
“Current row”
– moveToCurrentRow()

moveToCurrentRow()
updateable
row

moveToInsertRow()

InsertRow()
“InsertRow buffer”

Helia / Martti Laiho, 1998-2000


Deleting a Row

• Positioning in the ResultSet and deleting:


– <move method>
– deleteRow()

• Note:
– drivers handle deletions differently

Helia / Martti Laiho, 1998-2000


Refreshing the row

• Applies only to Cursor type:


– TYPE_SCROLL_SENSITIVE
• method
– refreshRow()

Helia / Martti Laiho, 1998-2000


Batch Updates

• Methods
– addBatch(“….”)
– …
– executeBatch();

• BatchUpdateException

Helia / Martti Laiho, 1998-2000


SQL-1999 Datatypes

• BLOB - binary large objects


• CLOB - character large objects
• SQL Array - of any SQL scalar datatype
• SQL structured type - User Defined Type UDT
• SQL REF - identifier

Helia / Martti Laiho, 1998-2000


JDBC 2.0 Standard Extension API

• JDBC 2.0 Standard Extension API


i.e. Optional Package API
– in javax.sql

– JavaBeans: Rowsets
– JNDI for naming and directory interface
– Connection Pooling
– Distributed Transactions: 2PC by Java Transaction API
(JTA)

Helia / Martti Laiho, 1998-2000

You might also like