'JDBC execute batch only executing last query
I'm trying to execute batch insert queries on MariaDB.
However, I am facing the problem that; I try to execute few insert queries, but only last one is executed.
Here is my code with Java:
private boolean fetchBatches(){
long[] resultSequences = null;
MkDbAccessor DA = new MkDbAccessor();
String befQuery = ConnectionChecker.regularQuery(ftpAttributes.getSqlControlName(), sqlControl.get(1).getServiceName(), false);
String query = ConnectionChecker.setQuery(befQuery);
DA.setBatch(query);
List<String[]> batches = new ArrayList<>();
for(currentIndex = 0; currentIndex < fileNames.length; currentIndex++){
if(fileNames[currentIndex] == null || fileNames[currentIndex].isEmpty()){
continue;
}
String[] reqValues = {ftpService.getControlName(), ftpService.getServiceName(), filePath, extension};
batches.add(reqValues);
}
try{
resultSequences = DA.executeBatch(batches);
} catch (SQLException e){
responseCode = 500;
responseMsg = new StringBuilder("Fail to fetch Database.");
return false;
}
return true;
}
// MkDatabaseAccessor.class
public void setBatch(String query){
try {
if (preparedStatement == null) {
preparedStatement = dbCon.prepareStatement(query, PreparedStatement.RETURN_GENERATED_KEYS);
}
} catch (SQLException se){
se.printStackTrace();
}
}
public long[] executeBatch(List<String[]> batches) throws SQLException{
ArrayList<Long> result = new ArrayList<>();
if(dbCon != null)
{
if(this.preparedStatement != null)
{
if(this.preparedStatement == null){
return null;
}
if(batches == null || batches.size() == 0){
return null;
}
try {
for (String[] values : batches) {
for (int i = 0; i < values.length; i++) {
preparedStatement.setString((i + 1), values[i]);
}
preparedStatement.addBatch();
}
} catch (SQLException se){
se.printStackTrace();
return null;
}
preparedStatement.executeBatch();
try(ResultSet generated = preparedStatement.getGeneratedKeys()){
if(generated.next()) {
result.add(generated.getLong(1));
}
}
if(preparedStatement != null)
preparedStatement.close();
if(dbCon != null)
dbCon.close();
}
}
return result.stream().mapToLong(l -> l).toArray();
}
And I'm trying to:
INSERT INTO STR_FILES (controller, service, directory, format) VALUES(?, ?, ?, ?);
And Values are:
set 1: 'free', 'text', 'board/1', 'jpg'
...
set 5: 'anonymous', 'comments', 'comment/1', 'jpg'
But I only query for set 5 is executed, whereas the others are not.
How can I execute batch queries? I read a lot of articles in Stack Overflow, and most problems are creating PreparedStatement
inside of loop that I am creating in outside of the loop.
And here is my SQL URI
String url = "jdbc:mysql://192.168.0.13:3306/Study?characterEncoding=UTF-8&serverTimezone=UTC&rewriteBatchedStatements=true&useBulkCopyForBatchInsert=true&autoReconnect=true&validationQuery=select 1;";
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|