隨筆 - 45, 文章 - 2, 評論 - 11, 引用 - 0
          數據加載中……

          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)  編輯  收藏 所屬分類: 數據庫


          只有注冊用戶登錄后才能發表評論。


          網站導航:
           
          主站蜘蛛池模板: 长泰县| 壶关县| 聂拉木县| 连云港市| 舒城县| 遵义市| 郧西县| 龙游县| 德钦县| 类乌齐县| 桐城市| 横峰县| 临朐县| 恩施市| 公安县| 诸城市| 台州市| 东阿县| 杨浦区| 阿拉善右旗| 衡山县| 醴陵市| 周口市| 东阿县| 扶余县| 神池县| 施甸县| 电白县| 常宁市| 环江| 湘阴县| 阳泉市| 荣成市| 青浦区| 宜宾县| 久治县| 彰武县| 竹山县| 新密市| 忻城县| 兴安县|