打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
使用JDBC的批处理功能
此范例有两个方法,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;
    }

}
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
JDBC
Java程序中连接池、及参数绑定实现
JDBC中的数据类型与日期问题
尚硅谷JDBC学习笔记
DBUtil的创建
从phoenix hbase谈谈研发管理和技术选型
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服