Home > Articles > Programming > Java

  • Print
  • + Share This

JDBC Core Components

Figure 3.5 illustrates the major classes of the JDBC API and how they relate to each other.

Figure 3.5 The major components of the JDBC API are shown here.

Of the major JDBC components, only DriverManager is a concrete Java class. The rest of the components are Java interfaces that are implemented by the various driver packages.


The DriverManager class keeps track of the available JDBC drivers and creates database connections for you. Although the JDBC driver itself creates the database connection, you usually go through the DriverManager to get the connection. That way you never need to deal with the actual driver class.

The DriverManager class has a number of useful static methods, the most popular of which is getConnection:

public static Connection getConnection(String url)
public static Connection getConnection(String url,
  String username, String password)
public static Connection getConnection(String url,
  Properties props)

The url parameter in the getConnection method is one of the key features of JDBC. It specifies what database you want to use. The general form of the JDBC URL is


The :driversubtype part of the URL is optional. You might just have a URL of the form


For an ODBC database connection, the URL takes the form


Consult the documentation for your JDBC driver to see the exact format of the driver's URL. The only thing you can count on is that it will start with jdbc:.

The DriverManager class knows about all the available JDBC drivers—at least the ones available in your program. There are two ways to tell the DriverManager about a JDBC driver. The first is to load the driver class. Most JDBC drivers automatically register themselves with the DriverManager as soon as their class is loaded (they do the registration using a static initializer). For example, to register the JDBC-ODBC driver that comes with the JDK, you can use the statement:


Although this method seems a little quirky, it's extremely common. Keep in mind that if the driver isn't in your classpath, the Class.forName method throws a ClassNotFoundException.

The other way to specify the available drivers is by setting the jdbc.drivers system property. This property is a list of driver class names separated by colons. For example, when you run your program, you might include the property

java -Djdbc.drivers=sun.jdbc.odbc.JdbcOdbcDriver:
[ccc]COM.cloudscape.core.JDBCDriver MyJDBCProgram

The DriverManager class also performs some other useful functions. Many database programs need to log data—especially database statements. Although you don't often log database statements in a production system, you frequently need to in a development environment. The setLogWriter method in the DriverManager class lets you specify a PrintWriter that will be used to log any JDBC-related information. The DriverManager class also supplies a println method for writing to the database log and a getLogWriter method to give you direct access to the log writer object.


The Driver interface is primarily responsible for creating database connections. The connect method returns a Connection object representing a database connection:

public Connection connect(String url, Properties props)


The Connection interface represents the core of the JDBC API. You can group most of the methods in the Connection interface into three major categories:

  • Getting database information

  • Creating database statements

  • Managing database transactions

Getting Database Information

The getMetaData method in the Connection interface returns a DatabaseMetaData object that describes the database. You can get a list of all the database tables and examine the definition of each table. You probably won't find the metadata too useful in a typical database application, but it's great for writing database explorer tools that gather information about the database.

Creating Database Statements

You use statements to execute database commands. There are three types of statements: Statement, PreparedStatement, and CallableStatement. Each of these statements works in a slightly different way, but the end result is always that you execute a database command.

The methods for creating a Statement are

public Statement createStatement()
public Statement createStatement(int resultSetType,
  int resultSetConcurrency)

When you create any kind of statement, you can specify a particular result set type and concurrency. These values determine how the connection handles the results returned by a query. Specifically, the resultSetType parameter lets you create a scrollable result set so you can move forward and backward through the results. By default, you can only move forward through the results. The resultSetConcurrency parameter lets you specify whether you can update the result set. By default, the result set is read-only.

The methods for creating a PreparedStatement are

public PreparedStatement prepareStatement(String sql)
public PreparedStatement prepareStatement(String sql,
  int resultSetType, int resultSetConcurrency)

The methods for creating a CallableStatement are

public CallableStatement prepareCall(String sql)
public CallableStatement prepareCall(String sql,
  int resultSetType, int resultSetConcurrency)

Managing Transactions

Normally, every statement you execute is a separate database transaction. Sometimes, however, you want to group several statements into a single transaction. The Connection class has an auto-commit flag that indicates whether it should automatically commit transactions or not. If you want to define your own transaction boundaries, call

public void setAutoCommit(boolean autoCommitFlag)

After you turn off auto-commit, you can start executing your statements. When you reach the end of your transaction, call the commit method to commit the transaction (complete it):

public void commit()

If you decide that you don't want to complete the transaction, call the rollback method to undo the changes made in the current transaction:

public void rollback()

When you are done with a connection, make sure you close it by calling the close method:

public void close()


As you now know, there are three different kinds of JDBC statements: Statement, PreparedStatement, and CallableStatement.

The Statement interface defines methods that allow you to execute an SQL statement contained within a string. The executeQuery method executes an SQL string and returns a ResultSet object, while the executeUpdate executes an SQL string and returns the number of rows updated by the statement:

ResultSet executeQuery(String sqlQuery)

You usually use executeQuery when you execute an SQL SELECT statement, and you use executeUpdate when you execute an SQL UPDATE, INSERT, or DELETE statement:

int executeUpdate(String sqlUpdate)

When you are done with a statement, make sure you close it. If not, you might soon run out of available statements. A database connection usually allows a specific number of open statements. If the garbage collector hasn't destroyed the old connections you aren't using, you might exceed the maximum number of statements. To close a statement, just call the statement's close method:

public void close()


When you close a Connection, it automatically closes any open statements or result sets.

Although the Statement interface contains a lot of methods for accessing results and setting various parameters, you will likely find that you only use the two execute methods and the close method in most of your applications.

Although the Statement interface is the simplest of the three statement interfaces, it can often cause you some programming headaches. Most of the time, you aren't executing exactly the same statement—you build a statement based on the data you are looking for or changing. In other words, you don't search for all people with a last name of Smith every time you do a query. You just search for all people with some specific last name.

If you just use the Statement interface, your query often looks something like this:

ResultSet results = stmt.executeQuery(
  "select * from Person where last_name = '"+

This code looks a little ugly because you've got the single quotes (for the SQL string) inside the double quotes for the Java string. Now, what happens if lastNameParam is O'Brien? Your SQL string would be

select * from Person where last_name = 'O'Brien'

The database would give you an error because you really need two single quotes in O'Brien (that is, O''Brien). You sometimes end up writing an escapeQuotes routine that looks for single quotes in a string and replaces then with two single quotes. Your executeQuery call would then look like this:

ResultSet results = stmt.executeQuery(escapeQuotes(
  "select * from Person where last_name = '"+

You can handle this much better by using a prepared statement. A prepared statement is an SQL statement with parameters you can change at any time. For example, you would create a prepared statement with your last name search using the following call:

PreparedStatement pstmt = myConnection.prepareStatement(
  "select * from Person where last_name = ?");

Now, when you go to perform the query, you use one of the set methods in the PreparedStatement interface to store the value for the parameter (the ? in the query string). You can have more than one parameter in a prepared statement. Now, to query for people whose last name is O'Brien, you use the following calls:

pstmt.setString(1, "O'Brien");
ResultSet results = pstmt.executeQuery();

The PreparedStatement interface has set methods for most Java data types and also allows you to store BLOBs and CLOBs using various data streams. The first parameter for each of the set methods is the parameter number. The first parameter is always 1 (not 0, as is the case with arrays and other data sequences). Also, to store a NULL value, you must indicate the data type of the column you are setting to NULL. For example, to set an integer value to NULL, use this call:

pstmt.setNull(1, Types.INTEGER);

The Types class contains constants that represent the various SQL data types supported by JDBC.

You can reuse a prepared statement. That is, after you have executed it, you can execute it again, or you can first change some of the parameter values and then execute it. Some applications create their prepared statements ahead of time, although many still create them when needed.

Usually, you can create the statements ahead of time only if you are using a single database connection, because statements are always associated with a specific connection. If you have a pool of database connections, you need to create the prepared statement when you actually need to use it, because you might get a different database connection from the pool each time.

The CallableStatement interface is used to access SQL stored procedures (SQL code stored on the database). The CallableStatement interface lets you invoke stored procedures and retrieve any results returned by the stored procedure. Stored procedures, incidentally, let you write queries that can run very quickly and are easy to invoke. It is often easier to update your application by changing a few stored procedures. The disadvantage, however, is that every database has a different syntax for stored procedures, so if you need to migrate from one database to another, you must rewrite all your stored procedures.


The Oracle database lets you write stored procedures in Java! You don't need to learn a new language to write Oracle stored procedures.

JDBC has a standard syntax for executing stored procedures, which takes one of two forms:

{call procedurename param1, param2, param3 ... }
{?= call procedurename param1, param2, param3 ... }

The parameters are optional. If your procedure doesn't take any parameters, the call might look like this:

{call myprocedure}

If your stored procedure returns a value, use the form that starts with ?=. You can also use ? for any of the parameter values in the stored procedure call and set them just like you set parameters in a PreparedStatement. In fact, the CallableStatement interface extends the PreparedStatement interface.

Some stored procedures have a notion of "out parameters," in which you pass a parameter in, the procedure changes the value of the parameter, and you need to examine the new value. If you need to retrieve the value of a parameter, you must tell the CallableStatement interface ahead of time by calling registerOutParameter:

public void registerOutParameter(int whichParameter, int sqlType)
public void registerOutParameter(int whichParameter, int sqlType,
  int scale)
public void registerOutParameter(int whichParameter, int sqlType,
  String typeName)

After you execute your stored procedure, you can retrieve the values of the out parameters by calling one of the many get methods. As with the set methods, the parameter numbers on the get methods are numbered starting from 1 and not 0. For example, suppose you have a stored procedure called findPopularName that searches the Person table for the most popular first name. Suppose, furthermore, that the stored procedure has a single out parameter that is the most popular name. You invoke the procedure this way:

CallableStatement cstmt = myConnection.prepareCall(
  "{call findPopularName ?}");
cstmt.registerOutParameter(1, Types.VARCHAR);
System.out.println("The most popular name is "+


The ResultSet interface lets you access data returned from an SQL query. The most common use of the ResultSet interface is just to read data, although you can also update rows and delete rows as of JDBC version 2.0. If you just want to read results, use the next method to move to the next row and then use any of the numerous get methods to retrieve the data. For example

ResultSet results = stmt.executeQuery(
  "select last_name, age from Person);
while (results.next())
  String lastName = results.getString("last_name");
  int age = results.getInt("age");

Each of the get methods in the ResultSet interface lets you specify which item you want by the column name or by the position in the query. For example, when you query for last_name, age, the last_name column is in the first position and age is in the second position. You can retrieve the last_name value with

String lastName = results.getString(1);

Retrieving a result by index is faster than retrieving a result by column name. When you retrieve a result by column name, the result set must first determine the index that corresponds to the column name. The disadvantage of using the index is that your code is a little harder to maintain. If you change the order of the columns or insert new columns, you must remember to update the indexes. If you use column names, you don't need to change existing code if you add new columns to the query or change the order of the columns. Use the column names when possible, but switch to using an index when you need to improve performance.


You can use the findColumn method in the result set to determine the index for a particular column name. If you have a query that returns a large number of rows, you should consider using findColumn to determine the indexes first, then retrieve the values using the index instead of the column name. Your program will be faster, but you still will have the benefits of using column names.

  • + Share This
  • 🔖 Save To Your Account

Related Resources

There are currently no related titles. Please check back later.