本節(jié)哼绑,我們?yōu)榇蠹医榻B下JDBC的批處理問題泪喊。
向student表中插入一萬條數(shù)據(jù)
package com.iotek.advance;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import com.iotek.common.ConnectionFactory;
import com.iotek.common.UtilsJdbc;
public class BatchTest {
public static void main(String[] args) {
Connection connection = null;
PreparedStatement preparedStatement = null;
int count = 0;
try {
connection = ConnectionFactory.getConnection();
connection.setAutoCommit(false);
String insertSQL = "INSERT INTO student VALUES (?,?,?,?,?)";
preparedStatement = connection.prepareStatement(insertSQL);
long time1 = System.currentTimeMillis();
for (int i = 0; i < 10000; i++) {
preparedStatement.setInt(1, i+1);
preparedStatement.setString(2, "zhangsan" + i);
preparedStatement.setString(3, "beijing" + i);
preparedStatement.setString(4, "male");
preparedStatement.setInt(5, 20);
preparedStatement.executeUpdate();
count++;
}
connection.commit();
long time2 = System.currentTimeMillis();
System.out.println("insert " + count + " rows takes " + (time2 - time1) + " ms");
} catch (SQLException e) {
e.printStackTrace();
try {
connection.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
} finally {
UtilsJdbc.close(connection, preparedStatement, null);
}
}
}
運行結果為:2556 ms
采用批處理方式插入數(shù)據(jù),關鍵方法是addBatch()和executeBatch()
package com.iotek.advance;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import com.iotek.common.ConnectionFactory;
import com.iotek.common.UtilsJdbc;
public class BatchTest {
public static void main(String[] args) {
Connection connection = null;
PreparedStatement preparedStatement = null;
int count = 0;
try {
connection = ConnectionFactory.getConnection();
connection.setAutoCommit(false);
String insertSQL = "INSERT INTO student VALUES (?,?,?,?,?)";
preparedStatement = connection.prepareStatement(insertSQL);
long time1 = System.currentTimeMillis();
for (int i = 0; i < 10000; i++) {
preparedStatement.setInt(1, i+1);
preparedStatement.setString(2, "zhangsan" + i);
preparedStatement.setString(3, "beijing" + i);
preparedStatement.setString(4, "male");
preparedStatement.setInt(5, 20);
preparedStatement.addBatch();
count++;
}
preparedStatement.executeBatch();
connection.commit();
long time2 = System.currentTimeMillis();
System.out.println("insert " + count + " rows takes " + (time2 - time1) + " ms");
} catch (SQLException e) {
e.printStackTrace();
try {
connection.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
} finally {
UtilsJdbc.close(connection, preparedStatement, null);
}
}
}
運行結果為:166 ms
由此搀突,我們可以看到批處理僅僅占用了之前寫法的零頭毫秒锰悼,大大提升了效率柳骄,所以在大量處理數(shù)據(jù)庫數(shù)據(jù)的時候团赏,最后使用批處理箕般,將參數(shù)或者是SQL語句,放到statement維護的緩存中舔清,然后統(tǒng)一丝里,在一次與數(shù)據(jù)庫的連接中,統(tǒng)一提交体谒,這樣可以大大提升性能杯聚。