Java Reference
In-Depth Information
The Connection class returned by the driver is a factory class that generates
many of the other classes required to perform database operations with JDBC. In
particular, the Connection class provides the facilities for processing SQL state-
ments, either by executing the statement directly or by returning an instance of a
class implementing Statement or one of the Statement subinterfaces.
A factory class is a popular design pattern. A factory class creates an object for you.
The factory pattern provides more control than the standard new operator. For ex-
ample, you might want to globally control each instance of a Connection object so
that when the system is rebooting, you can attempt to close all connections. If all
Connection objects are created by a single factory class, then that class will know
about each Connection that was created. Therefore, it can manage them properly
when the system is rebooting.
The Connection class also controls the various aspects of database transactions.
By default, new connections are in auto-commit mode . This means that each state-
ment that modifies the database is automatically committed if it succeeds. Unless
your requirements are relatively simple, auto-commit mode is not what you want.
If you require the data in multiple tables to be synchronized with each other, you
will want to turn auto-commit off, like this:
dbConnection.setAutoCommit(false);
Once auto-commit is off, you can perform transaction logic as you update the
database. Transaction logic, for example, enables you to roll back (or reverse) the
changes to one or more tables when the attempted update to another fails. The
tradeoff is that you must become very explicit about committing and rolling back
the updates. This is handled completely by the Connection class. As you might ex-
pect, the methods are called commit() and rollback() .
// Post the changes since the last commit or rollback.
dbConnection.commit();
// Reverse the changes since the last commit.
dbConnection.rollback();
I will discuss the methods in Connection that deal with statement processing
later. Some other methods in the Connection class are shown in the following table:
Search WWH ::




Custom Search