`
周一Monday
  • 浏览: 342514 次
  • 来自: 北京
社区版块
存档分类
最新评论

JDBC之批处理

阅读更多
package org.monday.demo;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import org.monday.util.JdbcUtil;

/**
 * 批处理
 */
public class BatchMain {

	public static void main(String[] args) {
		long start = System.currentTimeMillis();
		String sql = "insert into t_batch(id,name)values(?,?)";
		Connection conn = null;
		PreparedStatement pstmt = null;
		try {
			conn = JdbcUtil.getConnection();
			pstmt = conn.prepareStatement(sql);
			for (int i = 1; i <= 100003; i++) {
				pstmt.setInt(1, i);
				pstmt.setString(2, "name" + i);
				pstmt.addBatch(); // 加入批处理
				if (i % 1000 == 0) {
					pstmt.executeBatch(); // 处理
					pstmt.clearBatch(); // 清空处理(释放内存空间)
				}
				pstmt.executeBatch(); // 处理
			}
		} catch (SQLException e) {
			throw new RuntimeException(e);
		} finally {
			JdbcUtil.release(conn, pstmt, null);
		}
		long end = System.currentTimeMillis();
		System.out.println("耗时:" + ((end - start) / 1000) + "秒");

		// MySQL耗时99秒 Oracle耗时91秒
	}
}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics