我在學習 JDBC 批處理時, 為比較 Statement, PreparedStatement 和 JDBC Batch 操作之間的效率,寫一個例子:向數據庫中插入 100,000 條記錄,并記錄消耗的時間。然后分別用這三種方式實現,可每次測試的結果卻都是幾乎相同沒變化,請教大神這是為什么?
import org.junit.Test;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.Statement;
public class BatchTest {
/**
* 使用 Statement 進行批處理操作
*/
@Test
public void testBatchWithStatement(){
Connection connection = null;
Statement statement;
String sql;
try {
connection = JDBCUtils.getConnection();
JDBCUtils.beginTx(connection);
statement = connection.createStatement();
long start = System.currentTimeMillis();
for (int i = 0; i < 100000; i++) {
sql = "INSERT INTO batch VALUES(" + i +")";
statement.executeUpdate(sql);
}
long end = System.currentTimeMillis();
System.out.println(end - start);
JDBCUtils.commit(connection);
} catch (Exception e) {
e.printStackTrace();
JDBCUtils.rollback(connection);
}
}
/**
* 使用 PreparedStatement 進行批處理操作
*/
@Test
public void testBatchWithPreparedStatement(){
Connection connection = null;
PreparedStatement statement;
String sql;
try {
connection = JDBCUtils.getConnection();
JDBCUtils.beginTx(connection);
sql = "INSERT INTO batch VALUES(?)";
statement = connection.prepareStatement(sql);
long start = System.currentTimeMillis();
for (int i = 0; i < 100000; i++) {
statement.setInt(1, i + 1);
statement.executeUpdate();
}
long end = System.currentTimeMillis();
System.out.println(end - start);
JDBCUtils.commit(connection);
} catch (Exception e) {
e.printStackTrace();
JDBCUtils.rollback(connection);
}
}
/**
* 使用 Batch 進行批處理操作
*/
@Test
public void testBatch(){
Connection connection = null;
PreparedStatement statement;
String sql;
try {
connection = JDBCUtils.getConnection();
JDBCUtils.beginTx(connection);
sql = "INSERT INTO batch VALUES(?)";
statement = connection.prepareStatement(sql);
long start = System.currentTimeMillis();
for (int i = 0; i < 100000; i++) {
statement.setInt(1, i + 1);
statement.addBatch();
if ((i + 1) % 500 == 0){
statement.executeBatch();
statement.clearBatch();
}
}
if (100000 % 300 != 0){
statement.executeBatch();
statement.clearBatch();
}
long end = System.currentTimeMillis();
System.out.println(end - start);
JDBCUtils.commit(connection);
} catch (Exception e) {
e.printStackTrace();
JDBCUtils.rollback(connection);
}
}
}
添加回答
舉報
0/150
提交
取消