JavaData & JavaJDBC basics

JDBC basics

Developer.com content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.


June 8, 1999
JDBC basics

by Thornton Rose
(example programs by April Rose)

The Java Database Connectivity (JDBC) API is used to access databases from Java programs. There are several books available on the subject, but there are just a few things that you need to know to get started. In this article, we present the basics of using JDBC.

Tools

You will need the following tools to write Java programs that use JDBC:

  • JDK 1.1 or JDK 1.2 (Java 2)
  • A database
  • The JDBC driver for your database
  • Your favorite text editor.

Depending on the JDBC driver, the database can be anything from dBase files to Oracle. For this article, except for the section on stored procedures, tinySQL was used, because it is small and free (distributed under the GNU General Public License). tinySQL is a very minimal SQL engine that comes with a JDBC driver and supports the following SQL statements:

  • SELECT (simple joins, no aggregate functions, no nested queries)
  • UPDATE
  • INSERT
  • DELETE
  • CREATE TABLE
  • DROP TABLE

Driver

To communicate with your database using JDBC, you will need a JDBC driver. Usually you will get this from the database vendor, but there are several third-party drivers that work with most of the common databases (e.g., Oracle, Sybase). Also, you can use the JDBC-ODBC bridge if you are running your programs on Windows and are not doing anything too serious. The JDBC-ODBC bridge is a driver from Sun that allows Java programs to access databases via Microsoft’s ODBC (Open Database Connectivity) API.

Before you can connect to a database or execute any database statements, the JDBC driver must be loaded. The primary way to do this is to use the

Class.forName() method
. For tinySQL, it would like this:

Class.forName(“ORG.as220.tinySQL.textFileDriver”);
For the JDBC-ODBC bridge, it would look like this:

Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
You only have to do this once in your program. After the JDBC driver class has been loaded, it will be available via the DriverManager class, which is used to manage the JDBC drivers that have been loaded.

Connection

With the JDBC driver loaded, getting a connection is easy. You import the JDBC classes (which are in the java.sql package) and call the

getConnection()
method of the DriverManager class. However, you will have to look up the parameters for your JDBC driver. Here is fragment of code that gets a connection to a tinySQL database:

import java.sql.*;

Connection = DriverManager.getConnection(“jdbc:tinySQL”);

Here is another fragment that gets a connection to an ODBC data source via the JDBC-ODBC bridge:

Fragment 1

Additionally, here is a simple program that loads a JDBC driver, connects to a data source, then closes the connection.

Listing 1

Statements

Once you have an open connection to a database, you can extract and manipulate data using SQL (Structured Query Language) via database statements. You use the

Connection.createStatement()
to create a database statement, like this:

Statement dbStatement = dbConnection.createStatement();
Then, you use

Statement.executeQuery()
or

Statement.executeUpdate()
to execute the SQL statement, like this:

Listing 1a

Result sets

To extract data, you use a

SELECT
statement, executed via the

Statement.executeQuery()
method. This method returns a ResultSet object, which is a Java representation of the rows and columns of the data that results from the query. (You can think of it as a table.) To get the next available row, you call the

next()
method or the ResultSet object. To get a column you call the

ResultSet.getX()
, where “X” is the data type of the column (e.g.,

getInt()
). Here is a fragment of code that displays a result set:

Listing 1b

Note that you can also use column positions (in the result set) to retrieve columns values, like this:


dbResultSet.getInt(2); // get value of column 2
Here is a simple program that connects to a data source, executes some statements, then displays the contents of a result set:

Listing 2

Stored procedures

Some backend database servers, such as Oracle, provide the ability to store SQL procedures in the database. These procedures can then be executed by external programs to perform database operations. (This is often done to increase performance and to reduce application complexity.) To call a stored procedure using JDBC, you use the CallableStatement class,

Connection.prepareCall()
, and

Connection.execute()
. Here is an example program that calls a stored procedure in an Oracle database:

Listing 3

Stored procedures can have parameters and a return value. The positions of the return value and the parameters are specified in the statement with questions marks, like this:

Listing 3a

Both the return type and the types and values of the parameters must be registered before the procedure can be called. If a parameter or return value is going to come back from the stored procedure (often referred to as an “out” mode parameter), you register the type with

CallableStatement.registerOutParameter()
, like this:

Listing 3b

If the parameter is being sent into the procedure (often referred to as an “in” mode parameter), you set the value by calling the

CallableStatement.setX()
, where “X” is the type of the parameter, like this:

dbStoredProc.setString(2, displayName);
The return value is retrieved by calling

CallableStatement.getX()
, where “X” is the type of the return value, like this:

int reportKey = dbStoredProc.getInt(1);
Note that the first parameter of

registerOutParameter()
,

getX()
, and

setX()
is the position of the return value or parameter in the callable statement. For the callable statement shown above, the return value is in position 1, and the parameters are in positions 2 and 3.

Gotchas

  1. In an applet running in the Internet Explorer Java VM, sometimes the JDBC driver will not load properly using
    Class.forName()
    . A workaround is to instantiate the driver directly, then use it to get a Connection object, like this:

    Listing 4

  2. The JDBC-ODBC bridge is not multithreaded. This means that you cannot execute simultaneous statements or run asynchronous queries with the JDBC-ODBC bridge.
  3. Closing a statement or a connection can sometimes throw an exception. This is not a major problem, but it is something that should be handled in your programs.

Resources

About the authors

Thornton & April are contract software developers in Atlanta, Ga. Thornton can be reached via e-mail at trose@avana.net


Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories