JDBC批处理

本文介绍如何利用JDBC批处理功能在Durid连接池环境下插入大量数据,通过PreparedStatement的addBatch(), executeBatch()和clearBatch()方法提高数据库操作性能,以及如何配置Durid连接池以支持批处理。
摘要由CSDN通过智能技术生成
JDBC批处理
概述
	JDBC操作数据库的时候,需要一次性插入大量的数据的时候,如果
	每次只执行一条sql语句,效率就会很低。使用batch操作,每次批	
	量执行SQL语句,调高效率
	Statement和PrepareStatement都可以使用批处理
	PrepareStatement常用方法:
			addBatch(); //积攒sql语句
			executeBatch(); // 执行批处理
			clearBatch();  // 清空批处理
  • 首先在连接数据库的配置文件中加入如下代码
rewriteBatchedStatements=true

在这里插入图片描述

Durid连接池工具类
public class JDBCUtils_Durid {
    static DataSource dataSource =null;
    static ThreadLocal<Connection> tl = new ThreadLocal<>();
    static {
        Properties pro = new Properties();
        InputStream in = JDBCUtils_Durid.class.getClassLoader().getResourceAsStream("durid.properties");
        try {
            pro.load(in);
            dataSource = DruidDataSourceFactory.createDataSource(pro);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //    获取连接
    public static Connection getConnection() throws SQLException, IOException {
        Connection con = tl.get();
        if (con == null) {
            con = dataSource.getConnection();
            tl.set(con);
        }
        return  con;
    }


    //    释放连接
    public static void closeResource(ResultSet rs, Statement st, Connection con) throws SQLException {
        if (rs != null) {
            rs.close();
        }

        if (st != null) {
            st.close();
        }

        if (con != null) {
            tl.remove();
            con.close();
        }
    }
}
使用Durid连接池和batch批处理插入数据
public class Durid_batch {

    @Test
    public void test0() throws SQLException, IOException {
//        获取连接
        Connection con = JDBCUtils_Durid.getConnection();

        PreparedStatement ps = con.prepareStatement("insert into account values(?,null,?)");
        long startTime = System.currentTimeMillis();
        for (int i = 1; i < 10000; i++) {
            ps.setInt(1,i);
            ps.setDouble(2,i);
//            积攒 sql语句
            ps.addBatch();

//            如果除不尽的话,最后一部分不足3000的数据是不会被写入的
            if(i % 3000 == 0){
                System.out.println(i);
//                执行批处理
                ps.executeBatch();
//                清空批处理
//                ps.clearBatch();
            }
        }
//        处理最后一部分小于除数的数据
        ps.executeBatch();
        ps.clearBatch();

        long endTime = System.currentTimeMillis();
        System.out.println(endTime - startTime);

//        关闭连接
        JDBCUtils_Durid.closeResource(null,ps,con);
//       truncate table account 清空数据表
    }
}

引用:https://blog.csdn.net/lizhiqiang1217/article/details/90550465

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值