jdbc批處理方法
package cc.apl330; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import cc.apl330.dao.UserDAOException; //注意批處理在實際中應用要注意同時打包太多的處理會引起內存溢出. public class BatchTest { /** * @param args */ public static void main(String[] args) { long start = System.currentTimeMillis() ; //常規方式提交處理 for(int i=0; i<200; i++){ create(i) ; } long end = System.currentTimeMillis() ; System.out.println("crate:" + (end - start)) ; //成批提交處理 start = System.currentTimeMillis() ; create1() ; end = System.currentTimeMillis() ; System.out.println("Batchcrate:" + (end - start)) ; } //常規方式提交處理 static void create(int i){ String sql = "INSERT INTO USER(name,money) VALUES(?,?);"; Connection conn; PreparedStatement ps; try { conn = JdbcUtil.getConnection(); ps = conn.prepareStatement(sql) ; ps.setString(1, "name"+i) ; ps.setFloat(2, 200f+i) ; ps.executeUpdate(); JdbcUtil.free(null, ps, conn) ; } catch (SQLException e) { throw new UserDAOException(e.getMessage(),e) ; } } //成批提交處理 static void create1(){ String sql = "INSERT INTO USER(name,money) VALUES(?,?);"; Connection conn; PreparedStatement ps; try { conn = JdbcUtil.getConnection(); ps = conn.prepareStatement(sql) ; for(int i=200; i<400; i++){ ps.setString(1, "name"+i) ; ps.setFloat(2, 200f+i) ; ps.addBatch();//將處理打包 } //執行批處理 int[] is = ps.executeBatch() ; System.out.println(is.length+"") ; JdbcUtil.free(null, ps, conn) ; } catch (SQLException e) { throw new UserDAOException(e.getMessage(),e) ; } } }
posted on 2010-07-31 16:09 jack zhai 閱讀(188) 評論(0) 編輯 收藏 所屬分類: 數據庫