Created
November 21, 2021 07:10
-
-
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
This file contains 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
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