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


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


          網站導航:
           
          主站蜘蛛池模板: 河南省| 依兰县| 潢川县| 牡丹江市| 类乌齐县| 石家庄市| 湘阴县| 屏边| 凉城县| 容城县| 都匀市| 瑞金市| 浦城县| 鸡西市| 江源县| 天柱县| 胶州市| 通州区| 临夏县| 龙游县| 伊宁市| 扬中市| 奇台县| 祁门县| 湄潭县| 晋中市| 莱阳市| 渝北区| 伊吾县| 兴安盟| 长乐市| 江永县| 南江县| 衡阳县| 丹凤县| 天全县| 西峡县| 明水县| 大名县| 普安县| 苍山县|