Last active
July 4, 2023 12:00
-
-
Save kasramp/8c59d0c3d5edbb638072 to your computer and use it in GitHub Desktop.
Option-4 (Multi rows batch insertion)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public void insertStudents(List<Student> students) { | |
String initialInsertStatement = "INSERT INTO student VALUES"; | |
StringBuilder query = new StringBuilder(initialInsertStatement); | |
try (Connection connection = config.getConnection()) { | |
try (Statement statement = connection.createStatement()) { | |
for (int i = 0; i < students.size(); i++) { | |
if (i == 0) { | |
query.append(asSqlQuery(students.get(i))); | |
} else if (i % 200 != 0) { | |
query.append(",") | |
.append(asSqlQuery(students.get(i))); | |
} else { | |
statement.addBatch(query.toString()); | |
query = new StringBuilder(initialInsertStatement); | |
query.append(asSqlQuery(students.get(i))); | |
} | |
if (i % 1000 == 0) { | |
statement.executeBatch(); | |
System.out.println("Batch successfully inserted"); | |
} | |
i++; | |
} | |
statement.addBatch(query.toString()); | |
statement.executeBatch(); | |
} | |
} catch (SQLException e) { | |
throw new RuntimeException(e); | |
} | |
} | |
private static String asSqlQuery(Student student) { | |
return String.format("('%s','%s', %s)", student.getGuid(), student.getName(), student.getId()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment