分享

使用JDBC的批处理功能

 openwudi 2010-10-16
此范例有两个方法,create和createBatch。
批处理最主要的是效率提高,比一次次的处理数据所用的时间更短。
 
Java语言:
package cn.iego.wudi.jdbc;

import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;

public class BatchTest {

    public static void main(String[] args) throws Exception {
        //处理100条数据
        long start = System.currentTimeMillis();
        for (int i = 0; i < 100; i++) {
            create(i);
        }
        long end = System.currentTimeMillis();
        System.out.println("creat:"+(end-start));
       
        //100条数据批量处理
        start = System.currentTimeMillis();
        createBatch();
        end = System.currentTimeMillis();
        System.out.println("createBatch:"+(end-start));
    }
   
    //批处理
    private static void createBatch() {
        ResultSet rs = null;
        Connection conn = null;
        PreparedStatement ps =null;
        String sql = "insert into user(name,birthday,money) values (?,?,?)";
        try {
            //jdbcUtils.getConnection()为自建工具类,用于获得数据库连接
            conn = jdbcUtils.getConnection();
            ps = conn.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
            //100条数据加入批处理
            for (int j = 0; j < 100; j++) {
                ps.setString(1, "batch name " + j);
                ps.setDate(2, new Date(System.currentTimeMillis()));
                ps.setFloat(3, 2000 + j);
                ps.addBatch();
            }
            //执行批处理
            ps.executeBatch();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
   
    //普通处理
    public static int create(int i) throws Exception{
        ResultSet rs = null;
        Connection conn = null;
        PreparedStatement ps =null;
        String sql = "insert into user(name,birthday,money) values (?,?,?)";
        try {
            conn = jdbcUtils.getConnection();
            ps = conn.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
            ps.setString(1, "ps name "+i);
            ps.setDate(2, new Date(System.currentTimeMillis()));
            ps.setFloat(3, 2000+i);
            ps.executeUpdate();
            rs = ps.getGeneratedKeys();
           
            if (rs.next()) {
                return rs.getInt(1);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return -1;
    }

}

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多