批量,可以大大提高眾多增加、刪除、變化的步伐,它是有一個非常大的數據處理效率大收益。
的“連接池”相似。事實上就是先將多次操作(增刪改)打包。然后再一次發送運行
主要用到兩個方法:
Ø 打包:PreparedStatement.addBatch();
Ø 發送、運行:PreparedStatement.executeBatch();
以下看做同一件事。用批處理和不用批處理的效率對照,源代碼例如以下:
import java.sql.Connection; import java.sql.Date; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; /** * @author-zhipeng * * 對照批處理與非批處理的區別(本例的循環所在位置) */ public class BatchTest { /** * 對照“批處理”與“非批處理”的運行效率 */ public static void main(String[] args) throws SQLException { //非批處理,插入100條數據所花費的時間 long start = System.currentTimeMillis(); for (int i = 0; i < 100; i++) create(i); long end = System.currentTimeMillis(); System.out.println("create:" + (end - start)); //批處理。插入100條數據所花費的時間 start = System.currentTimeMillis(); createBatch(); end = System.currentTimeMillis(); System.out.println("createBatch:" + (end - start)); } /** * 非批處理-插入1條數據 */ static void create(int i) throws SQLException { Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; try { //JdbcUtils為自己定義的操作類,這里不多介紹 conn = JdbcUtils.getConnection(); String sql = "insert into user(name,birthday, money) values (?, ?, ?
) "; ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); ps.setString(1, "no batch name" + i); ps.setDate(2, new Date(System.currentTimeMillis())); ps.setFloat(3, 100f + i); //運行插入 ps.executeUpdate(); } finally { //釋放資源 JdbcUtils.free(rs, ps, conn); } } /** * 批處理-插入100條數據 */ static void createBatch() throws SQLException { Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; try { conn = JdbcUtils.getConnection(); String sql = "insert into user(name,birthday, money) values (?
, ?
, ?) "; ps = conn.prepareStatement(sql); //注意批處理與“非批處理”循環放的位置 for (int i = 0; i < 100; i++) { ps.setString(1, "batch name" + i); ps.setDate(2, new Date(System.currentTimeMillis())); ps.setFloat(3, 100f + i); //關鍵方法1:打包 ps.addBatch(); } //關鍵方法2:運行 int[] is = ps.executeBatch(); } finally { JdbcUtils.free(rs, ps, conn); } } }
執行效果:
這是運行100條數據的差距,能夠想象對大數據的效率提升改有多大。
版權聲明:本文博客原創文章。博客,未經同意,不得轉載。