JDBC

Basic Java
≈ 2 min read

A bridge between Java and a relational database

An application often needs to do more than keep objects in memory: it needs to read and modify data in a database, find a user, save an order, update a balance, or perform several related operations. JDBC is Java's standard API for communicating with relational databases.

JDBC defines a common set of interfaces, while a concrete driver translates those calls into the protocol of the selected DBMS. Because of this, Java code works with familiar objects such as Connection, PreparedStatement, and ResultSet instead of sending network packets to the database manually.

What this section covers

  • JDBC Basics. We will build the overall picture: driver, connection, SQL statement, and result processing.
  • Connection. We will examine the database connection object and its role in executing operations.
  • Statement and PreparedStatement. We will learn to send SQL and safely pass parameters into it.
  • ResultSet. We will see how to read rows and columns returned by a query.
  • JDBC Transactions. We will combine several changes into one operation with commit() and rollback().
  • Batch Operations. We will learn to send a series of similar commands without executing them one by one.
  • Generated Keys. We will retrieve values created by the database when a row is inserted, such as a new identifier.
  • Connection Pool. We will see why real applications reuse connections instead of constantly creating new ones.

The topics follow the natural path of a database request: first the application obtains a connection, then creates a command, executes it, and reads the result. After that, we will add transaction management and techniques that matter for performance and real server applications.

try (Connection connection = dataSource.getConnection()) {
    System.out.println(connection.isValid(2));
}

After this section, fragments like this will stop looking like a collection of infrastructure calls: you will understand which part of the work each object performs and where its responsibility ends.