Jdbc批量数据操作
package jdbc;
import org.junit.Test;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
public class PreparedStatementBatch {
@Test
public void test1() throws SQLException {
Connection connection = JdbcUtils.getConnection();
Statement statement = connection.createStatement();
for (int i = 1; i <= 20000; i++) {
String sql = "insert into goods(name) values('name_' + " + i + ")";
statement.executeUpdate(sql);
}
JdbcUtils.close(connection, statement);
}
@Test
public void test2() throws SQLException {
Connection connection = JdbcUtils.getConnection();
String sql = "insert into goods(name) values(?)";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
for (int i = 0; i < 20000; i++) {
preparedStatement.setObject(1, "name_" + i);
preparedStatement.execute();
}
JdbcUtils.close(connection, preparedStatement);
}
@Test
public void test3() throws SQLException {
Connection connection = JdbcUtils.getConnection();
String sql = "insert into goods(name) values(?)";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
for (int i = 0; i < 20000; i++) {
preparedStatement.setObject(1, "name_" + i);
preparedStatement.addBatch();
if (i % 500 == 0) {
preparedStatement.executeBatch();
preparedStatement.clearBatch();
}
}
JdbcUtils.close(connection, preparedStatement);
}
@Test
public void test4() throws SQLException {
Connection connection = JdbcUtils.getConnection();
connection.setAutoCommit(false);
String sql = "insert into goods(name) values(?)";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
for (int i = 0; i < 20000; i++) {
preparedStatement.setObject(1, "name_" + i);
preparedStatement.addBatch();
if (i % 1000 == 0) {
preparedStatement.executeBatch();
preparedStatement.clearBatch();
}
}
connection.commit();
JdbcUtils.close(connection, preparedStatement);
}
}