Sobes.tech
Junior

How is a request made to a database and how are the results processed?

sobes.tech AI

Answer from AI

A database query is performed using JDBC (Java Database Connectivity).

Main steps:

  1. Establishing a connection: Obtaining a Connection object via DriverManager.getConnection().
  2. Creating a Statement: Creating a Statement or PreparedStatement object to execute SQL queries. PreparedStatement is preferred for parameterized queries due to security and performance.
  3. Executing the query: Calling executeQuery() (for SELECT) or executeUpdate() (for INSERT, UPDATE, DELETE) on the Statement object.
  4. Processing results: If the query was SELECT, executeQuery() returns a ResultSet object. ResultSet allows step-by-step retrieval of data from the query result, moving through rows with next() and extracting column values by name or index using methods like getString(), getInt(), getDate(). For INSERT/UPDATE/DELETE, executeUpdate() returns the number of affected rows.
  5. Closing resources: It is important to close ResultSet, Statement, and Connection in reverse order (from the most nested to the outer) to free system resources. Use try-with-resources blocks for automatic closing.

Example of processing ResultSet:

// Assuming connection and preparedStatement are already established and created
String sql = "SELECT id, name, age FROM users WHERE status = ?";

try (PreparedStatement preparedStatement = connection.prepareStatement(sql)) {
    preparedStatement.setString(1, "active");

    try (ResultSet resultSet = preparedStatement.executeQuery()) {
        while (resultSet.next()) {
            int id = resultSet.getInt("id");
            String name = resultSet.getString("name");
            int age = resultSet.getInt("age");
            System.out.println("User: ID=" + id + ", Name=" + name + ", Age=" + age);
        }
    } // resultSet is closed automatically
} catch (SQLException e) {
    e.printStackTrace();
} // preparedStatement is closed automatically
// connection should also be closed, possibly in a finally block or a try-with-resources block above

When using ORM (e.g., Hibernate, Spring Data JPA), the process is abstracted. You work with entity objects, and ORM handles SQL generation and result mapping to objects.

Error handling is done using SQLException, which can be thrown at any stage of database interaction. Catching and logging exceptions is necessary.

How is a request made to a database and how are the… - sobes.tech