Introducing to JDBC

Summary: in this tutorial, you will learn about JDBC and its main components that you can use to interact with MySQL databases.

JDBC API provides a standard interface for interacting with any relational database management system (RDBMS).

JDBC API consists of the following main components:

  • JDBC Driver
  • Connection
  • Statement
  • ResultSet

Let’s take a look at each component in more detail.

JDBC Driver

A JDBC driver is a set of Java classes that implement JDBC interfaces for interacting with a specific database.

Almost all database vendors such as MySQL, Oracle, and Microsoft SQL Server, provide JDBC drivers. For example, MySQL provides a JDBC driver called MySQL Connector/J, allowing you to work with MySQL databases through a standard JDBC API.

There are three types of JDBC drivers:

  • JDBC-native API Driver
  • JDBC-net Driver
  • JDBC Driver.

In this tutorial, we’ll discuss the JDBC driver, for more detailed information on the other driver types, you can check out the JDBC driver.

JDBC Driver is written in pure Java. It translates JDBC calls into MySQL-specific calls and sends the calls directly to a specific database.

To use a JDBC driver, include the driver JAR file with your application. MySQL Connector/J is the JDBC driver.

Connection

The first and most important component of JDBC is the Connection object.

In a Java application, you first load a JDBC driver and then establish a connection to the database.

Through the Connection object, you can interact with the database such as creating a Statement to execute SQL queries against tables. You can open more than one connection to a database at the same time.

Statement

To execute an SQL query such as SELECT, INSERT, UPDATE, and DELETE you can use a Statement object. You create the Statement object through the Connection object.

JDBC provides several types of statements for different purposes such as PreparedStatement and CallableStatement.

ResultSet

After querying data from the database, you get a ResultSet object. The ResultSet object provides a set of APIs that allows you to traverse the query results.

Put it all together

The typical flow of using JDBC is as follows:

  1. First, load the JDBC driver and create a connection to the database.
  2. Then, create a Statement and execute the query to get a ResultSet.
  3. Next, traverse and process the ResultSet .
  4. Close the ResultSet , Statement , and Connection .
MySQL JDBC process flow

Summary

  • JDBC offers universal database access from Java.
  • Use MySQL connector/J as the driver to connect to MySQL from Java.
Was this tutorial helpful?