Home > Articles > Programming > Java

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.

DriverManager

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

jdbc:drivertype:driversubtype://params

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

jdbc:drivertype://params

For an ODBC database connection, the URL takes the form

jdbc:odbc:datasourcename

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:

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

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.

Driver

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)

Connection

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()

Statement

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()

NOTE

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 = '"+
  lastNameParam+"'");

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 = '"+
  lastNameParam+"'"));

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.

TIP

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);
cstmt.execute();
System.out.println("The most popular name is "+
  cstmt.getString(1));

ResultSet

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.

TIP

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.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020