/*
|
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
|
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
|
*/
|
package com.megatim.queryadhoc.queries;
|
|
import com.megatim.queryadhoc.contrat.DataColumn;
|
import com.megatim.queryadhoc.contrat.DataRow;
|
import com.megatim.queryadhoc.model.QueryParam;
|
import com.megatim.queryadhoc.contrat.DefaultPreparedStatementProcessor;
|
import com.megatim.queryadhoc.contrat.PreparedStatementProcessor;
|
import java.sql.Connection;
|
import java.sql.PreparedStatement;
|
import java.sql.SQLException;
|
import java.util.ArrayList;
|
import java.util.List;
|
|
/**
|
*
|
* @author ASUS
|
*/
|
public class CommonInsertQuery {
|
|
private final String tableName;
|
protected final Connection connection;
|
private final List<String> columnNames;
|
private final List<DataRow> rows;
|
private final int BATCH_SIZE = 1000;
|
|
public CommonInsertQuery(String tableName, final Connection connection, List<String> columnNames, List<DataRow> rows) {
|
this.tableName = tableName;
|
this.connection = connection;
|
this.columnNames = columnNames;
|
this.rows = rows;
|
}
|
|
public void execute() throws Exception {
|
|
try ( PreparedStatement statement = connection.prepareStatement(insertQueryString());) {
|
|
executeInBatch(statement, rows);
|
statement.executeBatch();
|
}
|
}
|
|
private String insertQueryString() {
|
|
StringBuilder query = new StringBuilder("INSERT INTO " + tableName + "(");
|
|
columnNames.forEach(column -> query.append(column).append(","));
|
|
query.replace(query.length() - 1, query.length(), ") VALUES(");
|
|
columnNames.forEach(s -> query.append("?,"));
|
|
query.replace(query.length() - 1, query.length(), ")");
|
|
return query.toString();
|
}
|
|
private void executeInBatch(PreparedStatement preparedStatement, List<DataRow> rows) throws SQLException, Exception {
|
|
int index = 0;
|
int count = 0;
|
|
for (DataRow row : rows) {
|
|
List<QueryParam> queryParameters = new ArrayList<>();
|
|
for (DataColumn dataColumn : row.columns()) {
|
queryParameters.add(new QueryParam(dataColumn.column(), dataColumn.value()));
|
}
|
|
PreparedStatementProcessor statementProcessor = new DefaultPreparedStatementProcessor(index);
|
statementProcessor.process(preparedStatement, queryParameters);
|
index = statementProcessor.lastProcessedIndex();
|
|
preparedStatement.addBatch();
|
|
if (++count % BATCH_SIZE == 0) {
|
preparedStatement.executeBatch();
|
}
|
|
}
|
|
}
|
}
|