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:
- Establishing a connection: Obtaining a
Connectionobject viaDriverManager.getConnection(). - Creating a Statement: Creating a
StatementorPreparedStatementobject to execute SQL queries.PreparedStatementis preferred for parameterized queries due to security and performance. - Executing the query: Calling
executeQuery()(for SELECT) orexecuteUpdate()(for INSERT, UPDATE, DELETE) on the Statement object. - Processing results: If the query was SELECT,
executeQuery()returns aResultSetobject.ResultSetallows step-by-step retrieval of data from the query result, moving through rows withnext()and extracting column values by name or index using methods likegetString(),getInt(),getDate(). For INSERT/UPDATE/DELETE,executeUpdate()returns the number of affected rows. - Closing resources: It is important to close
ResultSet,Statement, andConnectionin reverse order (from the most nested to the outer) to free system resources. Usetry-with-resourcesblocks 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.