JDBC ResultSet and PreparedStatement
JDBC provides ResultSet for retrieving data from SELECT queries and PreparedStatement
for executing parameterized queries. Let's explore these in-depth.
ResultSet:
A ResultSet represents the result set of a SELECT query. It provides methods to retrieve data
from the result set.
// Execute a SELECT query
ResultSet resultSet = statement.executeQuery("SELECT * FROM your_table");
// Process the result set
while (resultSet.next()) {
// Retrieve data from the result set
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
// Process the data as needed
}
Retrieving Data Types:
Use appropriate methods to retrieve data based on the column's data type.
int intValue = resultSet.getInt("int_column");
String stringValue = resultSet.getString("string_column");
Date dateValue = resultSet.getDate("date_column");
// Other data types
Handling NULL Values:
Use methods like getInt, getString, etc., to handle NULL values.
int intValue = resultSet.getInt("nullable_int_column");
if (resultSet.wasNull()) {
// Handle NULL value
}
PreparedStatement:
PreparedStatement is used for executing parameterized queries. It helps prevent SQL injection attacks
and improves performance.
// Create a PreparedStatement
PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO your_table (column1, column2) VALUES (?, ?)");
// Set values for parameters
preparedStatement.setString(1, "value1");
preparedStatement.setInt(2, 42);
// Execute the query
int rowsInserted = preparedStatement.executeUpdate();
Batch Processing with PreparedStatement:
You can use batch processing with PreparedStatement to execute multiple parameterized queries in a batch.
// Add queries to the batch
preparedStatement.setString(1, "value1");
preparedStatement.addBatch();
preparedStatement.setString(1, "value2");
preparedStatement.addBatch();
// Execute the batch
int[] batchResult = preparedStatement.executeBatch();
Generated Keys:
If your query generates keys (e.g., through auto-increment), you can retrieve them using
getGeneratedKeys().
// Execute an INSERT query that generates keys
PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO your_table (column1, column2) VALUES (?, ?)", Statement.RETURN_GENERATED_KEYS);
// Set values for parameters
preparedStatement.setString(1, "value1");
preparedStatement.setInt(2, 42);
// Execute the query
int rowsInserted = preparedStatement.executeUpdate();
// Retrieve generated keys
ResultSet generatedKeys = preparedStatement.getGeneratedKeys();
while (generatedKeys.next()) {
int generatedId = generatedKeys.getInt(1);
// Process the generated keys as needed
}
Note:
Always use PreparedStatement for executing parameterized queries to prevent SQL injection attacks
and improve performance. Handle ResultSet data types appropriately and consider NULL values.