What is JDBC? Introduction to Java Database Connectivity

JDBC (Java Database Connectivity) is the Java API that manages connecting to a database, issuing queries and commands, and handling result sets obtained from the database. Released as part of JDK 1.1 in 1997, JDBC was one of the earliest libraries developed for the Java language.

JDBC was initially conceived as a client-side API, enabling a Java client to interact with a data source. That changed with JDBC 2.0, which included an optional package supporting server-side JDBC connections. Every new JDBC release since then has featured updates to both the client-side package (java.sql) and the server-side package (javax.sql). JDBC 4.3, the most current version as of this writing, was released as part of Java SE 9 in September 2017 as JSR 221.

This article presents an overview of JDBC and JDBC drivers, followed by a hands-on introduction to using JDBC to connect a Java client to a lightweight relational database.

How JDBC works

As a developer, you can use JDBC to interact with a database from within a Java program. JDBC acts as a bridge from your code to the database, as shown in Figure 1.

JDBC connects Java programs to databases. IDG

Figure 1. JDBC connects Java programs to databases.

JDBC vs ODBC

Before JDBC, developers used Open Database Connectivity (ODBC), a language-agnostic standard approach to accessing a relational database management system, or RDBMS. In some ways, JDBC takes its inspiration from ODBC. The difference is that JDBC is Java-specific, offering a programming-level interface that handles the mechanics of Java applications communicating with a database.

JDBC’s architecture

The JDBC interface consists of two layers:

  1. The JDBC API supports communication between the Java application and the JDBC manager.
  2. The JDBC driver supports communication between the JDBC manager and the database driver.

The JDBC API and JDBC driver have been refined extensively over the years, resulting in a feature-rich, performant, and reliable library.

JDBC is the common API that your application code interacts with. Beneath that is the JDBC-compliant driver for the database you are using.

Figure 2 illustrates the JDBC architecture.

The JDBC interface consists of the JDBC API and its drivers. IDG

Figure 2. JDBC’s architecture consists of the JDBC API and JDBC drivers.

JDBC drivers

As an application programmer, you don’t need to immediately be concerned with the implementation of the driver you use, so long as it is secure and official. However, it is useful to be aware that there are four JDBC driver types:

  1. JDBC-ODBC bridge driver: A thin Java layer that uses an ODBC driver under the hood.
  2. Native API driver: Provides an interface from Java to the native database client.
  3. Middleware driver: A universal interface (“middleware”) between Java and the RDBMS’s vendor-specific protocol.
  4. Pure Java driver: A driver that implements the vendor-specific protocol directly in Java.

When you start thinking about architecture and performance, it will be beneficial to consider the type of driver you are using.

Simple database connections and queries

One of the benefits of programming in the Java ecosystem is that you will likely find a stable JDBC database connector for whatever database you choose. In this tutorial, we’ll use SQLite to get to know JDBC, mainly because it’s so easy to use.

The steps for connecting to a database with JDBC are as follows:

  1. Install or locate the database you want to access.
  2. Include the JDBC library.
  3. Ensure the JDBC driver you need is on your classpath.
  4. Use the JDBC library to obtain a connection to the database.
  5. Use the connection to issue SQL commands.
  6. Close the connection when you are finished.

We’ll go through these steps together.

Step 1. Download and install SQLite

SQLite is a very compact database. It isn’t intended for production use but is a great choice for quickly trying things out. SQLite uses a file as its functional database, without requiring any service or daemon installations.

To get started with this demonstration, first download the SQLite sample database. Unzip the .db file and save it somewhere you won’t forget. This file contains both a functional file-based database and sample schema and data that we can use.

Step 2. Import JDBC into your Java application

We could do our coding in an IDE, but coding directly in a text editor will better demonstrate JDBC’s simplicity. To begin, you will need to have a compatible JDK installation for your operating system.

Assuming you have a JDK installed, we can start by creating a simple Java program. In your text editor, paste in the code shown in Listing 1. Call this file WhatIsJdbc.java.

Listing 1. A simple Java program


class WhatIsJdbc{
  public static void main(String args[]){
      System.out.println("Hello InfoWorld");
  }
}

Now, compile the code by entering the command: javac WhatIsJdbc.java. Compiling will output the WhatIsJdbc.class file. Execute this file from the command line with the call: java WhatIsJdbc.

Once you have a basic Java program, you can include the JDBC libraries. Paste in the code from Listing 2 at the head of your simple Java program.

Listing 2. JDBC imports


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.ResultSet;
import java.sql.Statement;

Each of these imports provides access to a class that facilitates the standard Java database connection:

  • Connection represents the connection to the database.
  • DriverManager obtains the connection to the database. (Another option is DataSourceused for connection pooling.)
  • SQLException handles SQL errors between the Java application and the database.
  • ResultSet and Statement model the data result sets and SQL statements.

You’ll see each of these in action shortly.

Step 3. Add the JDBC driver to your classpath

Next, you’ll add the SQLite driver to your classpath. Remember, a JDBC driver is a class that implements the JDBC API for a specific database.

Go to the GitHub page for SQLite driver and download the latest SQLite .jar. If you are using Maven or Gradle, or something similar, you can add the driver via the Maven repository. Be sure to get the most recent .jar file and store it somewhere you’ll remember.

The next time you execute your Java program, you will pull in that .jar file via the classpath. There are several ways to set the classpath. Listing 3 shows how to do it using a command-line switch.

Listing 3. Executing the SQLite driver on the Java classpath


java.exe -classpath /path-to-driver/sqlite-jdbc-3.23.1.jar:. WhatIsJdbc

Notice that we’ve set the classpath to point at the driver and the local directory; this way, Java will still find our class file.

Step 4. Obtain a database connection

The classpath now has access to the driver. Next, change your simple Java application file to look like the program in Listing 4.

Listing 4. Using the JDBC Connection class to connect to SQLite


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.ResultSet;
import java.sql.Statement;

 String sql = "SELECT id, username FROM users WHERE id = ?";
    List users = new ArrayList<>();
    try (Connection con = DriverManager.getConnection(myConnectionURL);
         PreparedStatement ps = con.prepareStatement(sql)) {
        ps.setInt(1, userId);
        try (ResultSet rs = ps.executeQuery()) {
            while(rs.next()) {
                users.add(new User(rs.getInt("id"), rs.getString("name")));
            }
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return users;

class WhatIsJdbc{
  public static void main(String[] args) {
    String url = "jdbc:sqlite:path-to-db/chinook/chinook.db";
    try (Connection conn = DriverManager.getConnection(url){

      System.out.println("Got it!");

    } catch (SQLException e) {
      throw new Error("Problem", e);
    } 
  }
}

Compile and execute this code. Assuming all goes well, you will get an affirming message.

Now, we’re ready for some SQL commands.

Step 5. Query the database

With the live connection object in hand, we can do something useful, like querying the database. Listing 5 shows how to query SQLite using the JDBC Connection and Statement objects.

Listing 5. Querying the database with JDBC


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.ResultSet;
import java.sql.Statement;


class WhatIsJdbc{
  public static void main(String[] args) {
    String sql = "SELECT id, username FROM users WHERE id = ?";
    String url = "jdbc:sqlite:path-to-db-file/chinook/chinook.db";
    try (Connection conn = DriverManager.getConnection(url);
      Statement stmt = conn.createStatement()) {

      try {
        ResultSet rs = stmt.executeQuery("select * from albums";);
        while (rs.next()) {
          String name = rs.getString("title");
          System.out.println(name);
        }
      } catch (SQLException e ) {
            throw new Error("Problem", e);
      } 

    } catch (SQLException e) {
      throw new Error("Problem", e);
    } 
  }
}

In Listing 5 we use our Connection object to obtain a Statement object: conn.createStatement(). We then use this object to execute an SQL query: stmt.executeQuery(query).

The executeQuery command returns a ResultSet object, which we then use to iterate over the data with while (rs.next()). In this example, you should see the album titles we’ve queried on as output.

Notice that we also closed the connection, via a call to conn.close().

PreparedStatements, batch updates, and transactions

So far, we’ve covered the basics of using JDBC to connect to a database and issue SQL commands. While Statements and ResultSets work well for common scenarios, you’ll likely need additional options for larger or more complex applications. Fortunately, the JDBC library continues evolving to meet most database access needs.

Leave a Comment