Java Data Base Connectivity, provide Java programs with a way to connect to
and use relational databases. The JDBC API lets you invoke SQL commands from
Java programming language methods. In simplest terms, JDBC allows to do three
things
- Establish a connection with a database
- Send SQL statements
- Process the results
The following code fragment gives a simple example of these three steps:
Connection con = DriverManager.getConnection(
"jdbc:myDriver:wombat", "myLogin", "myPassword");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM Table1");
while (rs.next()) {
int x = rs.getInt("a");
String s = rs.getString("b");
float f = rs.getFloat("c");
}
Before the version 2.0 of JDBC, only local transactions controlled by the transaction
manager of the DBMS is possible. To code a JDBC transaction, you invoke the
commit and rollback methods of the java.sql.Connection interface. The beginning
of a transaction is implicit. A transaction begins with the first SQL statement
that follows the most recent commit, rollback, or connect statement. (This rule
is generally true, but may vary with DBMS vendor.). The following example illustrates
how transactions are managed by the JDBC API.
public void withdraw (double amount) {
try {
//A connection opened with JDBC is an AUTO COMMIT mode meaning
// that the commitment is automatically performed when the connection
// is closed
//setAutoCommit to false disable this feature
connection.setAutoCommit(false);
//perform an SQL update to Withdraw money from account
connection.commit();
} catch (Exception ex) {
try {
connection.rollback();
throw new Exception("Transaction failed: " + ex.getMessage());
} catch (Exception sqx) {
throw new Exception(...}
}
}
}
From the version 2.0, a JDBC driver can be involved within a distributed transaction
since it supports the XAResource interface that allows to participate to the
2PC protocol. An application that need to include more than one database can
create a JTA transaction. To demarcate a JTA transaction, the application program
invokes the begin, commit, and rollback methods of the javax.transaction.UserTransaction
interface. The following code, that can be applied to a bean-managed transaction,
demonstrates the UserTransaction methods. The begin and commit invocations delimit
the updates to the database. If the updates fail, the code invokes the rollback
method and throws an Exception.
public void transfer(double amount) {
UserTransaction ut = context.getUserTransaction();
try {
ut.begin();
// Perform SQL command to debit account 1
// Perform SQL command to debit account 2
ut.commit();
} catch (Exception ex) {
try {
ut.rollback();
} catch (Exception ex1) {
throw new Exception ("Rollback failed: " + ex1.getMessage());
}
throw new Exception ("Transaction failed: " + ex.getMessage());
}
}