随笔 - 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 阅读(172) 评论(0)  编辑  收藏 所属分类: 数据库


只有注册用户登录后才能发表评论。


网站导航: