Do not create the "values" part using string concatenation, as it opens up the possibility for SQL Injection attacks.
I would use a prepared expression here. You can create your request as follows:
List<String> columns = Arrays.asList("column1", "column2", "column3"); String columnsFragment = columns.stream().collect(Collectors.joining(",")); String placeholdersFragment = columns.stream().filter(s -> "?").collect(Collectors.joining(",")) String insertStatement = String.format("INSERT INTO ifc.documents (%s) VALUES (%s) ", columnsFragment, placeholdersFragment);
And then use insertStatement with PreparedStatement :
PreparedStatement st = connection.prepareStatement(insertStatement); for (int i = 0; i < values.size(); i++) {
In this case, the resulting query will look like
INSERT INTO ifc.documents (column1, column2, column3) VALUES (?, ?, ?)
source share