JDBC makes it possible to do establish a connection with a data source, send queries and update statements, and process the results.
Simply, JDBC makes it possible to do the following things within a Java application:
- Establish a connection with a data source
- Send queries and update statements to the data source
- Process the results
The following figure shows the components of the JDBC model.
The Java application calls JDBC classes and interfaces to submit SQL statements and retrieve results.
The JDBC API is implemented through the JDBC driver. The JDBC Driver is a set of classes that implement the JDBC interfaces to process JDBC calls and return result sets to a Java application. The database (or data store) stores the data retrieved by the application using the JDBC Driver.
The main objects of the JDBC API include:
- A DataSource object is used to establish connections. Although the Driver Manager can also be used to establish a connection, connecting through a DataSource object is the preferred method.
- A Connection object controls the connection to the database. An application can alter the behavior of a connection by invoking the methods associated with this object. An application uses the connection object to create statements.
- Statement, PreparedStatement, and CallableStatement objects are used for executing SQL statements. A PreparedStatement object is used when an application plans to reuse a statement multiple times. The application prepares the SQL it plans to use. Once prepared, the application can specify values for parameters in the prepared SQL statement. The statement can be executed multiple times with different parameter values specified for each execution. A CallableStatement is used to call stored procedures that return values. The CallableStatement has methods for retrieving the return values of the stored procedure.
- A ResultSet object contains the results of a query. A ResultSet is returned to an application when a SQL query is executed by a statement object. The ResultSet object provides methods for iterating through the results of the query.
For an excellent introduction to JDBC, take a look at Chapter 2 of "Java Enterprise in a Nutshell - An Introduction to JDBC" by Jim Farley, William Crawford, and David Flanagan (Second Edition April 2002) available online here.