Jdbc introduction

59
JDBC (Java Database Connectivity) Rakesh Ray

Transcript of Jdbc introduction

Page 1: Jdbc introduction

JDBC

(Java Database Connectivity)

Rakesh Ray

Page 2: Jdbc introduction

Contents

Overview

History of JDBC

JDBC Model

JDBC Driver Type

JDBC Programming Steps

Step 1 : Loading a JDBC Driver

Step 2 : Connecting to a Database

Step 3 : Executing SQL

Step 4 : Processing the Results

Step 5 : Closing Database Connection

The PreparedStatement Object

Transaction and JDBC

Summary

Online Resources

Page 3: Jdbc introduction

Overview (1/2)

JDBC

JDBC is a standard interface for connecting to relational databases from Java

The JDBC Classes and Interfaces are in the java.sqlpackage

JDBC is Java API for executing SQL statements

Provides a standard API for tool/database developers

Possible to write database applications using a pure Java API

Easy to send SQL statements to virtually any relational database

What does JDBC do?

Establish a connection with a database

Send SQL statements

Process the results

JDBC DriverJAVA Applet/

Application DatabaseJDBC Call

DatabaseCommand

Page 4: Jdbc introduction

Overview (2/2)

Reason for JDBC Database vendors (Microsoft Access, Oracle etc.) provide

proprietary (non standard) API for sending SQL to the server and receiving results from it

Languages such as C/C++ can make use of these proprietary APIs directlyHigh performanceCan make use of non standard features of the databaseAll the database code needs to be rewritten if you change

database vendor or product JDBC is a vendor independent API for accessing relational data from

different database vendors in a consistent way

Page 5: Jdbc introduction

History of JDBC (1/2)

JDBC 1.0 released 9/1996.

Contains basic functionality to connect to database, query database, process results

JDBC classes are part of java.sql package

Comes with JDK 1.1

JDBC 2.0 released 5/1998

Comes with JDK 1.2

javax.sql contains additional functionality

Additional functionality:

Scroll in result set or move to specific row

Update database tables using Java methods instead of SQL commands

Send multiple SQL statements to the database as a batch

Use of SQL3 datatypes as column values

Page 6: Jdbc introduction

History of JDBC (2/2)

JDBC 3.0 released 2/2002

Comes with Java 2, J2SE 1.4

Support for:

Connection pooling

Multiple result sets

Prepared statement pooling

Save points in transactions

Page 7: Jdbc introduction

JDBC Model

JDBC consists of two parts:

JDBC API, a purely Java-based API

JDBC driver manager

Communicates with vendor-

specific drivers

JAVA Applet/

Application

JDBC API

Driver Manager

Driver API

Vendor Specific

JDBC DriverJDBC-ODBC Bridge

Database

Vender Specific

ODBC Driver

Database

Java

Application

Developer

JDBC

Developer

Vender

Specific JDBC

developer

Page 8: Jdbc introduction

JDBC Driver Type

JDBC-ODBC bridge plus ODBC driver

Native-API partly-Java driver

JDBC-Net pure Java driver

Native Protocol pure Java API driver

Page 9: Jdbc introduction

JDBC-ODBC bridge plus ODBC driver

Type 1 drivers act as a "bridge" between JDBC and another database connectivity mechanism such as ODBC. The JDBC- ODBC bridge provides JDBC

access using most standard ODBC drivers.

Functions:

Translates query obtained by JDBC into corresponding ODBC query, which is

then handled by the ODBC driver.

Sun provides a JDBC-ODBC Bridge driver. sun.jdbc.odbc.JdbcOdbcDriver. This

driver is native code and not Java, and is closed

source.

Client -> JDBC Driver -> ODBC Driver -> Database

There is some overhead associated with the translation work to go from JDBC to ODBC.

Page 10: Jdbc introduction

Native-API partly-Java driver

Type 2 Java to Native API. Drivers that are written partly in the Java programming language and partly in native code. This is faster than the type 1 driver. This can’t use in applet as native code can’t be executed by applet.

Functions:

This type of driver converts JDBC calls into calls to the client API for that database.

Client -> JDBC Driver -> Vendor Client DB Library -> Database

Page 11: Jdbc introduction

Advantages and Disadvantages Advantage

Better performance than Type 1 since no jdbc to odbc translation is needed.

Disadvantages

The vendor client library needs to be installed on the client machine.

Cannot be used in internet due the client side software needed.

Not all databases give the client side library.

Page 12: Jdbc introduction

JDBC-Net pure Java driver

This driver translates JDBC calls into a DBMS-independent net-protocol, which is

then translated to a DBMS protocol by a server. This net server middleware is able

to connect its pure Java clients to many different databases. The specific protocol

used depends on the vendor.

Page 13: Jdbc introduction

Native-protocol pure Java driver:

This kind of driver converts JDBC calls directly into the network protocol used by

DBMSs. This allows a direct call from the client machine to the DBMS server and is

an excellent solution for intranet access.

Functions

Type 4 drivers are entirely written in Java that communicate directly with a

vendor's database through socket connections. No translation or middleware

layers, are required, improving performance.

The driver converts JDBC calls into the vendor-specific database protocol so that

client applications can communicate directly with the database server.

Completely implemented in Java to achieve platform independence.

e.g include the widely used Oracle thin driver - oracle.jdbc.driver. OracleDriver

which connect to jdbc:oracle:thin URL format.

Client Machine -> Native protocol JDBC Driver -> Database server

Page 14: Jdbc introduction

Advantages & Disadvantage

Advantages

These drivers don't translate the requests into db request to ODBC or pass it to client

api for the db, nor do they need a middleware layer for request indirection. Thus the performance is considerably improved.

Disadvantage

At client side, a separate driver is needed for each database.

Page 15: Jdbc introduction

JDBC Programming Steps

Connect

Query

Process Results

Close

1) Register the driver

2) Create a connection to the database

1) Create a statement

2) Query the database

1) Get a result set

2) Assign results to Java variables

1) Close the result set

2) Close the statement

3) Close the connection

Page 16: Jdbc introduction

Skeleton Code

Class.forName(DRIVERNAME);

Connection con = DriverManager.getConnection(

CONNECTIONURL, DBID, DBPASSWORD);

Statement stmt = con.createStatement();

ResultSet rs = stmt.executeQuery(“SELECT a, b, c FROM member);

While(rs.next())

{

Int x = rs.getInt(“a”);

String s = rs.getString(“b”);

Float f = rs.getFloat(“c”);

}

rs.close();

stmt.close();

con.close();

Loading a JDBC driver

Connecting to a database

Processing the result set

Closing the connections

Executing SQL

Page 17: Jdbc introduction

Examplepublic class JdbcDemo {

public static void main(String[] args) {

Connection con=null;

Statement st=null;

ResultSet rs=null;

try{

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

con=DriverManager.getConnection("jdbc:odbc:ora", "system", "manager");

st=con.createStatement();

rs=st.executeQuery("select * from EMP");

while(rs.next())

System.out.print("Name : "+rs.getString("name")+"\nSalary : "+rs.getFloat("sal"));

rs.close();

st.close();

con.close();

}catch (ClassNotFoundException e) {

e.printStackTrace();

}catch(SQLException sql){

sql.printStackTrace();

}

}

}

Page 18: Jdbc introduction

Step 1 : Loading a JDBC Driver

A JDBC driver is needed to connect to a database

Loading a driver requires the class name of the driver.

Ex) JDBC-ODBC: sun.jdbc.odbc.JdbcOdbcDriver

Oracle driver: oracle.jdbc.driver.OracleDriver

MySQL: com.mysql.jdbc.Driver

Loaing the driver class

Class.forName("com.mysql.jdbc.Driver");

DriverManager.registerDriver(new com.mysql.jdbc.Driver());

It is possible to load several drivers.

The class DriverManager manages the loaded driver(s)

Page 19: Jdbc introduction

Step 2 : Connecting to a Database (1/2)

JDBC URL for a database

Identifies the database to be connected

Consists of three-part:

jdbc:<subprotocol>:<subname>

Protocol: JDBC is

the only protocol in

JDBC

Protocol: JDBC is

the only protocol in

JDBC

Subname: indicates the location and

name of the database to be

accessed. Syntax is driver specific

Subname: indicates the location and

name of the database to be

accessed. Syntax is driver specific

Sub-protocol:

identifies a

database

driver

Sub-protocol:

identifies a

database

driver

Ex)

jdbc:mysql://oopsla.snu.ac.kr/myd

b

Page 20: Jdbc introduction

JDBC URLVendor of database, Location of

database server and name of

database

Username Password

Step 2 : Connecting to a Database (2/2)

The DriverManager allows you to connect to a database using the specified JDBC driver, database location, database name, username and password.

It returns a Connection object which can then be used to communicate with the database.

Connection connection =

DriverManager.getConnection("jdbc:mysql://oopsla.snu.ac.kr/mydb",“useri

d",“password");JDBC URL

Vendor of database, Location of

database server and name of

database

Username Password

Page 21: Jdbc introduction

DriverManager class

The DriverManager class acts as an interface between user and drivers. It keeps track of the

drivers that are available and handles establishing a connection between a database and

the appropriate driver.

Commonly used methods of DriverManager

1) public static void registerDriver(Driver driver): is used to register the given driver with

DriverManager.

2) public static void deregisterDriver(Driver driver):is used to deregister the given driver (drop

the driver from the list) with DriverManager.

3) public static Connection getConnection(String url): is used to establish the connection with

the specified url.

4) public static Connection getConnection(String url, Properties prop): is used to establish

connection with URL and properties which contains userid and password.

4) public static Connection getConnection(String url,String userName,String password): is

used to establish the connection with the specified url, username and password.

Page 22: Jdbc introduction

Database URL & Driver Name

RDBMS JDBC driver name URL format

MySQL com.mysql.jdbc.Driver jdbc:mysql://hostname/ databaseName

ORACLE oracle.jdbc.driver.OracleDriver jdbc:oracle:thin:@hostname:port Number:databaseName

DB2 COM.ibm.db2.jdbc.net.DB2Dri

verjdbc:db2:hostname:port Number/databaseName

Sybase com.sybase.jdbc.SybDriver jdbc:sybase:Tds:hostname: port Number/databaseName

JDBC-

ODBC Bri

dge

jdbc:odbc:<DB> sun.jdbc.odbc.JdbcOdbcDriver

SQL Serv

er

jdbc:weblogic:mssqlserver4:<D

B>@<HOST>:<PORT>weblogic.jdbc.mssqlserver4.Driver

Page 23: Jdbc introduction

Step 3 : Executing SQL (1/2)

Statement object

Can be obtained from a Connection object

Sends SQL to the database to be executed

Statement has three methods to execute a SQL statement:

executeQuery() for QUERY statements

Returns a ResultSet which contains the query results

executeUpdate() for INSERT, UPDATE, DELETE, or DDL statements

Returns an integer, the number of affected rows from the SQL

execute() for either type of statement

Statement statement = connection.createStatement();

Page 24: Jdbc introduction

Statement stmt = conn.createStatement();

ResultSet rset = stmt.executeQuery

("select RENTAL_ID, STATUS from ACME_RENTALS");

Statement stmt = conn.createStatement();

int rowcount = stmt.executeUpdate

("delete from ACME_RENTAL_ITEMS

where rental_id = 1011");

Step 3 : Executing SQL (2/2)

Execute a select statement

Execute a delete statement

Page 25: Jdbc introduction

Connection InterfaceA Connection is the session between java application and database. This is the factory of Statement,

PreparedStatement, CallableStatement, DatabaseMetaData and also manage Transaction by

several methods.

Commonly used methods

public Statement createStatement(): creates a statement object that can be used to execute SQL

queries.

public Statement createStatement(int resultSetType,int resultSetConcurrency): Creates a Statement

object that will generate ResultSet objects with the given type and concurrency.

public PreparedStatement prepareStatement(String): Create a preparedStatement object that can

be used for execute SQL query.

public CallableStatement prepareCall(String): Create a CallableStatement object that can be used

for execute stored procebure.

public void setAutoCommit(boolean status): is used to set the commit status.By default it is true.

public void commit(): saves the changes made since the previous commit/rollback permanent.

public void rollback(): Drops all changes made since the previous commit/rollback.

public void close(): closes the connection and Releases a JDBC resources immediately.

Page 26: Jdbc introduction

Statement interface

The Statement interface provides methods to execute queries with the database.

Commonly used methods

public ResultSet executeQuery(String sql): is used to execute SELECT query. It returns the object of ResultSet.

public int executeUpdate(String sql): is used to execute specified query, it may be create, drop, insert, update, delete etc.

public boolean execute(String sql): is used to execute queries that may return multiple

results.

public int[] executeBatch(): is used to execute batch of commands.

Page 27: Jdbc introduction

Step 4 : Processing the Results (1/2)

JDBC returns the results of a query in a ResultSet object

ResultSet object contains all of the rows which satisfied the conditions in an SQL statement

A ResultSet object maintains a cursor pointing to its current row of data

Use next() to step through the result set row by row

next() returns TRUE if there are still remaining records

getString(), getInt(), and getXXX() assign each value to a Java variable

Record 1 Record 2 Record 3 Record 4

ResultSetInternal Pointer

The internal pointer starts one before the first

record

Page 28: Jdbc introduction

Step 4 : Processing the Results (2/2)

Example

Statement stmt = con.createStatement();

ResultSet rs = stmt.executeQuery(“SELECT ID, name, score FROM table1”);

While (rs.next()){

int id = rs.getInt(“ID”);

String name = rs.getString(“name”);

float score = rs.getFloat(“score”);

System.out.println(“ID=” + id + “ ” + name + “ ” + score);}

NOTE You must step the cursor to the first record before read the results

This code will not skip the first record

ID name score

1 James 90.5

2 Smith 45.7

3 Donald 80.2

Table1

Output

ID=1 James 90.5

ID=2 Smith 45.7

ID=3 Donald 80.2

Page 29: Jdbc introduction

Step 5 : Closing Database Connection

It is a good idea to close the Statement and Connection objects when you have finished with them

Close the ResultSet object

rs.close();

Close the Statement object

stmt.close();

Close the connection

connection.close();

Page 30: Jdbc introduction

ResultSet Interface

A ResultSet is a Java object that contains the results of executing an

SQL query.

The data stored in a ResultSet object is retrieved through a set of get

methods that allows access to the various columns of the current row.

A result set is also a table with rows and columns, but it contains only

the column values from a database table that satisfy the conditions of

a query

Each record contains the same amount of columns, although not all

columns may have a value. A column can have a null value

Page 31: Jdbc introduction

Creating a ResultSet

You create a ResultSet by executing a Statement or PreparedStatement

Statement statement = connection.createStatement();

ResultSet result = statement.executeQuery("select * from people");

String sql = "select * from people";

PreparedStatement statement = connection.prepareStatement(sql);

ResultSet result = statement.executeQuery();

Page 32: Jdbc introduction

Iterating the ResultSet

To iterate the ResultSet you use its next() method.

The next() method returns true if the ResultSet has a next

record, and moves the ResultSet to point to the next record. If

there were no more records, next() returns false

while(result.next()) {

// ... get column values from this record

}

Page 33: Jdbc introduction

Navigation Methods

Method Description

absolute() Moves the ResultSet to point at an absolute position. The

position is a row number passed as parameter to

the absolute() method.

afterLast() Moves the ResultSet to point after the last row in

the ResultSet.

beforeFirst() Moves the ResultSet to point before the first row in

the ResultSet.

first() Moves the ResultSet to point at the first row in the ResultSet.

last() Moves the ResultSet to point at the last row in the ResultSet.

next() Moves the ResultSet to point at the next row in the ResultSet.

previous() Moves the ResultSet to point at the previous row in

the ResultSet.

relative() Moves the ResultSet to point to a position relative to its

current position. The relative position is passed as a

parameter to the relative method, and can be both positive

and negative.

Page 34: Jdbc introduction

Navigation Methods for position

Method Description

getRow() Returns the row number of the current row - the row currently

pointed to by the ResultSet.

getType() Returns the ResultSet type.

isAfterLast() Returns true if the ResultSet points after the last row. False if

not.

isBeforeFirst() Returns true if the ResultSet points before the first row. False if

not.

isFirst() Returns true if the ResultSet points at the first row. False if not.

Page 35: Jdbc introduction

ResultSet Types

there are three ResultSet types

ResultSet.TYPE_FORWARD_ONLY: ResultSet can only be navigated forward. That is,

you can only move from row 1, to row 2, to row 3 etc.

ResultSet.TYPE_SCROLL_INSENSITIVE:

ResultSet can be navigated (scrolled) both forward and backwards.

You can also jump to a position relative to the current position, or jump to an absolute

position.

The ResultSet is insensitive to changes in the underlying data source while the ResultSet is

open.

ResultSet.TYPE_SCROLL_SENSITIVE:

ResultSet can be navigated (scrolled) both forward and backwards.

You can also jump to a position relative to the current position, or jump to an absolute

position.

The ResultSet is sensitive to changes in the underlying data source while the ResultSet is

open.

The default type is TYPE_FORWARD_ONLY

Page 36: Jdbc introduction

ResultSet Concurrency

The ResultSet concurrency determines whether the ResultSet can be

updated, or only read.

The DatabaseMetaData.supportsResultSetConcurrency(int concurrency)

method returns true or false depending on whether the given concurrency

mode is supported or not.

ResultSet can have one of two concurrency levels

ResultSet.CONCUR_READ_ONLY: means that the ResultSet can only be read.

ResultSet.CONCUR_UPDATABLE:means that the ResultSet can be both read and

updated.

Page 37: Jdbc introduction

ResultSet Holdability

The ResultSet holdability determines if a ResultSet is closed when the commit()

method of the underlying connection is called.

DatabaseMetaData.supportsResultSetHoldability(int holdability) returns true or false depending on whether the given holdability mode is supported or not.

There are two types of holdability:

ResultSet.CLOSE_CURSORS_OVER_COMMIT: means that all ResultSet instances are

closed when connection.commit() method is called on the connection that

created the ResultSet.

ResultSet.HOLD_CURSORS_OVER_COMMIT: means that the ResultSet is kept open

when the connection.commit() method is called on the connection that created

the ResultSet. this might be useful if you use the ResultSet to update values in the

database.

Page 38: Jdbc introduction

Retrieving Column Values

The getter methods in the ResultSet interface (getInt, getString, and so on)

provide the means for retrieving column values from the current row.

column values should be read only once if not scrollable.

the column name or the column number can be used to designate the column

from which to retrieve data.

String s = rs.getString(2);

String s = rs.getString("TITLE");

Information about the columns in a ResultSet is available by calling the

method ResultSet.getMetaData().

Accoring to the datatype used for column we have to use corresponding

getter method.

Page 39: Jdbc introduction

Providing Performance

Many DBMSs and drivers are optimized to give the best performance under various circumstances,

which means that generally a database programmer is best advised to use their default settings.

The number of rows that should be fetched from the database each time new rows are needed: The

number of rows to be fetched is called the fetch size, and it can be set by two different methods:

Statement and ResultSet.

setFetchSize and ResultSet.setFetchSize

Statement stmt = con.createStatement();

stmt.setFetchSize(25);

ResultSet rs = stmt.executeQuery(SELECT * FROM EMPLOYEES);

rs.setFetchSize(50);//code changes thefetch size of rs to 50

The direction in which rows will be processed: The interface ResultSet defines the following three

constants for specifying the direction in which to process rows:FETCH_FORWARD, FETCH_REVERSE,

and FETCH_UNKNOWN

Statement stmt = con.createStatement();

stmt.setFetchDirection(FETCH_REVERSE);

ResultSet rs = stmt.executeQuery(SELECT * FROM EMPLOYEES);

rs.setFetchDirection(FETCH_FORWARD);//code changes the fetch direction of rs to forward.

Page 40: Jdbc introduction

Example: Creating Different Types of ResultSets

a default ResultSet object, one that is forward-only and uses read-only

concurrency.

we can set a ResultSet scrollabele, sensitive, updatable and holdable by

following statements

Connection con = DriverManager.getConnection("jdbc:my_subprotocol:my_subname");

Statement stmt = con.createStatement( ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE), ResultSet.HOLD_CURSORS_OVER_COMMIT);

stmt.setFetchSize(25);

ResultSet rs2 = stmt.executeQuery("SELECT EMP_NO, SALARY FROM EMPLOYEES");

Page 41: Jdbc introduction

Example update method 1/2

A ResultSet object may be updated (have its rows modified, inserted, or

deleted) programmatically if its concurrency type is CONCUR_UPDATABLE.

rs.updateInt(3, 88); // the value in column 3 of rs is set to 88

rs.updateInt("SCORES", 88);// the value in column SCORES of rs is set to 88

rs.updateRow();//to update in database

move to a specific row and update value

rs.absolute(4);

rs.updateString("ADDRESS", "321 Kasten");

rs.updateFloat("AMOUNT", 10101.0f);

rs.updateRow();

we can also delete the current row

rs.deleteRow();

Page 42: Jdbc introduction

Example update method 2/2

Insert Row can be done using following steps

rs.moveToInsertRow();

rs.updateObject(1, myArray);

rs.updateInt(2, 3857);

rs.updateString(3, "Mysteries");

rs.insertRow();

rs.first();

First we have to set the ResultSet in insert mode.

Then we set value for columns

Then save the result through insertRow()

Then set corsor to fetch mode.

Page 43: Jdbc introduction

The PreparedStatement Object

The PreparedStatement interface inherits from Statement. PreparedStatement objects are precompiled, their execution can be faster than that of Statement

objects.Differs from it in two ways.

Instances of PreparedStatement contain an SQL statement that has already been compiled

The SQL statement contained in a PreparedStatement object may have one or more IN parameters. IN parameters are given by "?"

The PreparedStatement's primary features are:

Easy to insert parameters into the SQL statement.

Easy to reuse the PreparedStatement with new parameters.

May increase performance of executed statements.

Enables easier batch updates.

Page 44: Jdbc introduction

The PreparedStatement Object

// Create the prepared statement

PreparedStatement pstmt =

con.prepareStatement(“

UPDATE table1 SET status = ? WHERE id =?”)

// Supply values for the variables

pstmt.setString (1, “out”);

pstmt.setInt(2, id);

// Execute the statement

pstmt.executeUpdate();

Page 45: Jdbc introduction

Reusing a PreparedStatement

String sql = "update people set firstname=? , lastname=? where id=?";

PreparedStatement preparedStatement =

connection.prepareStatement(sql);

preparedStatement.setString(1, "Gary");

preparedStatement.setString(2, "Larson");

preparedStatement.setLong (3, 123);

int rowsAffected = preparedStatement.executeUpdate();

preparedStatement.setString(1, "Stan");

preparedStatement.setString(2, "Lee");

preparedStatement.setLong (3, 456);

int rowsAffected = preparedStatement.executeUpdate();

Page 46: Jdbc introduction

Batch Updates

A batch update is a batch of updates grouped together, and sent to the database in one "batch", rather than sending the updates one by one.

Sending a batch of updates to the database in one go, is faster than

sending them one by one, waiting for each one to finish. There is less

network traffic involved in sending one batch of updates (only 1 round trip),

and the database might be able to execute some of the updates in parallel.

The speed up compared to executing the updates one by one, can be

quite big.

You can batch both SQL inserts, updates and deletes. It does not make

sense to batch select statements.

There are two ways to execute batch updates:

Using a Statement

Using a PreparedStatement.

Page 47: Jdbc introduction

Statement Batch Updates

You can use a Statement object to execute batch updates. You do so using the addBatch() and executeBatch() methods.

The int[] array returned by the executeBatch() method is an array of int

telling how many records were affected by each executed SQL statement in

the batch. Here is an example:

Statement statement = null;

try{

statement = connection.createStatement();

statement.addBatch("update people set firstname='John' where id=123");

statement.addBatch("update people set firstname='Eric' where id=456");

statement.addBatch("update people set firstname='May' where id=789");

int[] recordsAffected = statement.executeBatch();

} finally {

if(statement != null) statement.close();

}

Page 48: Jdbc introduction

PreparedStatement Batch Updates

String sql = "update people set firstname=? , lastname=? where id=?";

PreparedStatement preparedStatement = null;

try{

preparedStatement = connection.prepareStatement(sql);

preparedStatement.setString(1, "Gary"); preparedStatement.setString(2, "Larson");

preparedStatement.setLong (3, 123);

preparedStatement.addBatch();

preparedStatement.setString(1, "Stan"); preparedStatement.setString(2, "Lee");

preparedStatement.setLong (3, 456);

preparedStatement.addBatch();

int[] affectedRecords = preparedStatement.executeBatch();

}finally {

if(preparedStatement != null) {

preparedStatement.close();

}

}

Page 49: Jdbc introduction

Transactions and JDBC (1/3)

The classic example of when transactions are necessary is the example of bank

accounts. You need to transfer $100 from one account to the other. You do so

by subtracting $100 from the first account, and adding $100 to the second

account. If this process fails after you have subtracted the $100 from the first

bank account, the $100 are never added to the second bank account. The

money is lost in cyber space.

Transaction: more than one statement that 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 = cancel all actions

Page 50: Jdbc introduction

Transactions and JDBC (2/3)

Connection connection = ...

try{

connection.setAutoCommit(false);

// create and execute statements etc.

connection.commit();

} catch(Exception e) {

connection.rollback();

} finally {

if(connection != null) {

connection.close();

}

}

Page 51: Jdbc introduction

Transactions and JDBC (3/3) A Savepoint object marks an intermediate point within a transaction and makes it possible

to roll back the transaction to that point instead of rolling back the entire transaction.

Connection con = ...try{

con.setAutoCommit(false);Statement stmt = con.createStatement();int rows = stmt.executeUpdate("INSERT INTO AUTHORS VALUES " + "(LAST, FIRST, HOME)

'TOLSTOY', 'LEO', 'RUSSIA'");Savepoint save1 = con.setSavepoint("SAVEPOINT_1");rows = stmt.executeUpdate("INSERT INTO AUTHORS VALUES " + "(LAST, FIRST, HOME) 'MELVOY',

'HAROLD', 'FOOLAND'");con.commit();

} catch(Exception e) {con.rollback(save1);

} finally {if(connection != null) {

con.close();}

}

Page 52: Jdbc introduction

CallableStatement

A CallableStatement object provides a way to call stored procedures in a standard way

for all DBMSs.

variable number of parameters used for input (IN parameters), output (OUT parameters), or

both (INOUT parameters). A

question mark serves as a placeholder for a parameter.

Creating a CallableStatement

CallableStatement callableStatement = connection.prepareCall("{call calculateStatistics(?, ?)}");

Setting IN Parameter Values

callableStatement.setString(1, "param1");

callableStatement.setInt (2, 123);

OUT Parameters

callableStatement.registerOutParameter(1, java.sql.Types.VARCHAR);

callableStatement.registerOutParameter(2, java.sql.Types.INTEGER);

Page 53: Jdbc introduction

CallableStatement

Retrieve OUT parameter

String s = callableStatement.getString(1);

int i = callableStatement.getInt(2);

INOUT Parameters

CallableStatement cstmt = con.prepareCall("{call reviseTotal(?)}");

callableStatement.setInt(1, 25);

callableStatement.registerOutParameter(1, java.sql.Types.INTEGER);

callableStatement.executeUpdate();

int x = callableStatement.getInt(1);

Executing the CallableStatement

ResultSet result = callableStatement.executeQuery();

callableStatement.executeUpdate();

Page 54: Jdbc introduction

DatabaseMetaData

Through the java.sql.DatabaseMetaData interface you can obtain meta data about the database you have connected.

Obtaining a DatabaseMetaData Instance

DatabaseMetaData databaseMetaData = connection.getMetaData();

Database Product Name and Version

String productName = databaseMetaData.getDatabaseProductName();

String productVersion = databaseMetaData.getDatabaseProductVersion();

Database Driver Version

int driverMajorVersion = databaseMetaData.getDriverMajorVersion();

int driverMinorVersion = databaseMetaData.getDriverMinorVersion();

Listing Tables

ResultSet result = databaseMetaData.getTables(catalog, schemaPattern, tableNamePattern, types );

Page 55: Jdbc introduction

Java Bean

This is a regular java Object, typically used for modeling data.

This class coded according to the JavaBeans API specifications.

This is also known as POJO(Plain Old Java Object)

characteristics of a JavaBean

It provides a default, no-argument constructor.

It should be serializable and implement the Serializable interface.

It may have a number of properties which can be read or written.

It may have a number of "getter" and "setter" methods for the

properties.

Page 56: Jdbc introduction

JavaBeans Properties

A JavaBean property is a named attribute that can be accessed by

the user of the object.

A JavaBean property may be read, write, read only, or write only.

JavaBean properties are accessed through two methods

getPropertyName(): if property name is firstName, your method name would be getFirstName() to read that property. This method

is called accessor.

setPropertyName(): if property name is firstName, your method

name would be setFirstName() to write that property. This method

is called mutator.

Page 57: Jdbc introduction

JavaBeans Properties Rules

First letter should small letter.

First letter should capital in getter and setter method.

Property can be

Read only

Write only

Read and writer

Property type should be same for getter and setter.

Getter should not have arguments

Setter should have one argument.

Page 58: Jdbc introduction

JavaBeans Examplepackage com.cutm;

public class StudentsBean implements java.io.Serializable

{

private String firstName = null;

private String lastName = null;

private int age = 0;

public StudentsBean() { }

public String getFirstName(){ return firstName; }

public String getLastName(){ return lastName; }

public int getAge(){ return age; }

public void setFirstName(String firstName){ this.firstName =

firstName; }

public void setLastName(String lastName){ this.lastName =

lastName; }

public void setAge(Integer age){ this.age = age; }

}

Page 59: Jdbc introduction

Online Resources

Sun’s JDBC site

http://java.sun.com/products/jdbc/

JDBC tutorial

http://java.sun.com/docs/books/tutorial/jdbc/

http://tutorials.jenkov.com/jdbc/index.html

List of available JDBC drivers

http://developers.sun.com/product/jdbc/drivers

API for java.sql

http://java.sun.com/j2se/1.5.0/docs/api/java/sql/package-summary.html