Skip to content

Chapter 31 of 37

JDBC Database Connectivity

Connect safely with DataSource, prepared statements, result sets, and transactions.

46 minutes 10 quick checksBy Subha Prasad
Lesson 31 of 37Course navigation

Lesson content

Read, practise, then check your understanding

JDBC standardizes relational database access. Prefer a configured pooled DataSource; close connections, statements, and result sets with try-with-resources.

Parameters and transactions

String sql = "select name from users where id = ?";
try (Connection connection = dataSource.getConnection();
     PreparedStatement statement = connection.prepareStatement(sql)) {
    statement.setLong(1, id);
    try (ResultSet rows = statement.executeQuery()) {
        if (rows.next()) return rows.getString("name");
    }
}

Prepared statements separate values from SQL and prevent injection. For multi-step work, disable auto-commit, commit success, and roll back failure. Define isolation, timeouts, batch behavior, null mapping, and generated-key handling. Never share a Connection across concurrent operations unless explicitly supported.

Knowledge check

Answer every question correctly to complete this chapter.

Which statement best describes DataSource?
Which Java term matches this description: A preferred configurable factory for database connections.
Which statement best describes Connection?
Which Java term matches this description: A database session controlling statements and transactions.
Which statement best describes PreparedStatement?
Which Java term matches this description: A parameterized precompiled statement that resists SQL injection.
Which statement best describes ResultSet?
Which Java term matches this description: A cursor over rows returned by a query.
Which statement best describes transaction?
Which Java term matches this description: A unit of work committed atomically or rolled back.

0 of 10 checks passed

Your progress is saved on this device.