Skip to content
Ameen Abozaid
Planned lessonJNR-025-L01

From DriverManager to DataSource

  • Lesson 1 of 5
  • Junior
On This Lesson 4 topics

This lesson is planned. The outline below lists the topics it will cover. The full lesson has not been published yet.

In this lesson

get database connections from a pool instead of opening one per statement.

Planned topics

  • JDBC is Java's standard API to talk to SQL databases; a driver (JAR) speaks the database's protocol.
  • DriverManager.getConnection(...) opens a brand-new connection each time: slow (network, login, setup).
  • A DataSource hands out connections; a pool (for example HikariCP) keeps them open and reuses them.
  • "Closing" a pooled connection returns it to the pool; always use try-with-resources.
  • Never open one connection per statement.
Draft outline details

Demonstration

java
try (Connection c = dataSource.getConnection();
     PreparedStatement ps = c.prepareStatement("select id, name from product where id = ?")) {
    ps.setLong(1, 42L);
    try (ResultSet rs = ps.executeQuery()) {
        if (rs.next()) System.out.println(rs.getString("name"));
    }
}

Check your understanding

What does close() do on a pooled connection?

Show answer

Returns it to the pool; the real connection stays open.

Practice

Apply this lesson with the module's lab, exercises and quiz.

Lab and exercises Quiz

Marking a lesson complete is optional and you can undo it any time. Your progress stays in this browser.

Continue to next lesson

Type to search levels, phases, modules and lessons.