Skip to content

Instantly share code, notes, and snippets.

@alexradzin
Created November 21, 2021 07:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexradzin/f6d818a93a47e7d5986c9d6a58444d1f to your computer and use it in GitHub Desktop.
Save alexradzin/f6d818a93a47e7d5986c9d6a58444d1f to your computer and use it in GitHub Desktop.
Insert rows to a database using regular and prepared statement utilizing one-by-one and batch mode
package org.jdbc.test;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import static java.lang.String.format;
public class Insert {
private final Connection connection;
public Insert(Connection connection) {
this.connection = connection;
}
public void insert(String[] texts) throws SQLException {
for (int i = 0; i < texts.length; i++) {
try (Statement statement = connection.createStatement()) {
statement.executeUpdate(format(
"insert into my_table (id, text) values (%d, '%s')",
i + 1,
texts[i]));
}
}
try (Statement statement = connection.createStatement()) {
for (int i = 0; i < texts.length; i++) {
statement.addBatch(format(
"insert into my_table (id, text) values (%d, '%s')",
i + 1,
texts[i]));
}
statement.executeBatch();
}
try (PreparedStatement ps = connection.prepareStatement(
"insert into my_table (id, text) values (?, ?)")) {
for (int i = 0; i < texts.length; i++) {
ps.setInt(1, i + 1);
ps.setString(2, texts[i]);
}
ps.executeUpdate();
}
try (PreparedStatement ps = connection.prepareStatement(
"insert into my_table (id, text) values (?, ?)")) {
for (int i = 0; i < texts.length; i++) {
ps.setInt(1, i + 1);
ps.setString(2, texts[i]);
ps.addBatch();
}
ps.executeUpdate();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment