I am working on a Java application where I need to execute a batch of SQL queries using JDBC's PreparedStatement. I have encountered an issue where the PreparedStatement seems to clear the batch every time it is initialized with a new query. Here is the relevant portion of my code:
@Transactional
public int[] executeBatchQuery(String code, List<String> queries, List<List<String>> parametersList) throws Exception {
Map<String, String> errorMap = new HashMap<>();
int[] count = {};
if (queries.size() != parametersList.size()) {
logger.info("Both lists length is not equal");
return null;
}
PreparedStatement pstmt = null;
Connection connection = null;
try {
connection = dataSource.getConnectionByCode(code);
for (int i = 0; i < queries.size(); i++) {
String query = queries.get(i);
List<String> parameters = parametersList.get(i);
pstmt = connection.prepareStatement(query);
// Set parameters for the prepared statement
for (int j = 0; j < parameters.size(); j++) {
pstmt.setString(j + 1, parameters.get(j));
}
pstmt.addBatch();
}
if (pstmt != null) {
count = pstmt.executeBatch();
}
else {
throw new SQLException();
}
}
catch (SQLException exception) {
logger.info("Roll back successfully executed");
logger.info("printing StackTrace: ");
exception.printStackTrace();
errorMap.put("mBoolean", "true");
errorMap.put("errorMessage", exception.getMessage());
}
finally {
try {
if (pstmt != null) {
pstmt.close();
}
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
return count;
}
In the list of queries, each query is different, with varying columns, WHERE clauses, and sometimes different tables
I have noticed that every time I initialize the PreparedStatement with a new query, it clears the batch. This behavior is not desirable for my application, as I need to execute multiple queries in a batch. Can someone suggest a workaround or an alternative approach to prevent the PreparedStatement from clearing the batch every time it is initialized with a new query?
I attempted to execute a batch of SQL queries using JDBC's PreparedStatement in a Java application. The goal was to add multiple queries to the batch and execute them together for efficiency.
Specifically, I initialized a PreparedStatement object and iterated through a list of queries, adding each query to the batch using the addBatch() method. I then expected the PreparedStatement to retain all the queries in the batch, allowing me to execute them in one go.
However, despite adding multiple queries to the batch, I observed that only the last query added to the batch was being executed. It seems that each time the PreparedStatement was initialized with a new query, it cleared the batch, resulting in only the latest query being executed.
I expected all the queries in the batch to be executed sequentially, but this was not the case. Instead, only the last query in the batch was executed, disregarding the previous queries.