JDBC Executing SQL Queries

JDBC allows you to execute SQL queries from your Java application. Let's explore the different types of queries and their execution in-depth.

Select Query:

Use the executeQuery method to execute SELECT queries. The result is returned as a ResultSet that you can iterate over to retrieve the data.


// 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
}

Insert, Update, and Delete Queries:

Use the executeUpdate method to execute INSERT, UPDATE, and DELETE queries. It returns the number of affected rows.


// Execute an INSERT query
int rowsInserted = statement.executeUpdate("INSERT INTO your_table (column1, column2) VALUES (value1, value2)");

// Execute an UPDATE query
int rowsUpdated = statement.executeUpdate("UPDATE your_table SET column1 = value1 WHERE id = 1");

// Execute a DELETE query
int rowsDeleted = statement.executeUpdate("DELETE FROM your_table WHERE id = 1");

Batch Processing:

JDBC supports batch processing for executing multiple queries in a batch. Use the addBatch method to add queries to the batch and executeBatch to execute them.


// Add queries to the batch
statement.addBatch("INSERT INTO your_table (column1) VALUES (value1)");
statement.addBatch("UPDATE your_table SET column1 = value2 WHERE id = 1");

// Execute the batch
int[] batchResult = statement.executeBatch();

PreparedStatement:

PreparedStatement is used to execute 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();

CallableStatement:

CallableStatement is used to execute stored procedures. It can also be used for parameterized queries with output parameters.


// Create a CallableStatement
CallableStatement callableStatement = connection.prepareCall("{CALL your_stored_procedure(?, ?)}");

// Set values for parameters
callableStatement.setString(1, "inputValue");

// Register output parameters
callableStatement.registerOutParameter(2, Types.VARCHAR);

// Execute the stored procedure
callableStatement.execute();

// Retrieve output parameter value
String outputValue = callableStatement.getString(2);

Note:

Always use parameterized queries to prevent SQL injection attacks. Use PreparedStatement for improved performance and security.