使用PreparedStatement批量操作数据

17 篇文章 0 订阅

一、批量执行SQL语句

当需要成批插入或者更新记录时,可以采用Java的批量更新机制,这一机制允许多条语句一次性提交给数据库批量处理。通常情况下比单独提交处理更有效率

JDBC的批量处理语句包括下面三个方法:

  • addBatch(String):添加需要批量处理的SQL语句或是参数;
  • executeBatch():执行批量处理语句;
  • clearBatch():清空缓存的数据

通常我们会遇到两种批量执行SQL语句的情况:

  • 多条SQL语句的批量处理;
  • 一个SQL语句的批量传参;

二、使用PreparedStatement批量插入数据

@Test
    public void testInsert1(){
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        try {

            long start = System.currentTimeMillis();

            connection = JDBCUtils.getConnection();

            String sql = "insert into goods(name)values(?)";

            preparedStatement = connection.prepareStatement(sql);

            for (int i = 0; i < 20000; i++) {
                preparedStatement.setObject(1,"name_" + i);
                preparedStatement.execute();
            }

            long end = System.currentTimeMillis();

            System.out.println("花费的时间为:" + (end - start));

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.closeResource(connection,preparedStatement);
        }
    }

花费时间为
在这里插入图片描述
优化插入操作,减少磁盘IO操作。使用addBatch()executeBatch()clearBatch()三个方法实现批处理。mysql服务器默认是关闭批处理的,我们需要通过一个参数,让mysql开启批处理的支持。将?rewriteBatchedStatements=true 写在配置文件的url后面。

url=jdbc:mysql://localhost:3306/test?rewriteBatchedStatements=true
	@Test
    public void testInsert2(){
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        try {

            long start = System.currentTimeMillis();

            connection = JDBCUtils.getConnection();

            String sql = "insert into goods(name)values(?)";

            preparedStatement = connection.prepareStatement(sql);

            for (int i = 0; i < 20000; i++) {
                preparedStatement.setObject(1,"name_" + i);

                //1、暂时缓存sql,缓存一定数量之后再与数据库交互,进行插入
                preparedStatement.addBatch();

                if(i % 500 == 0){       //缓存500个sql,执行一次数据库插入的交互

                    //2、执行batch
                    preparedStatement.executeBatch();

                    //3、清空batch
                    preparedStatement.clearBatch();
                }

            }

            long end = System.currentTimeMillis();

            System.out.println("花费的时间为:" + (end - start));

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.closeResource(connection,preparedStatement);
        }
    }

花费时间
在这里插入图片描述
还可以再优化,设置不自动提交,等到所有数据都传输完成以后,最后一块提交。

@Test
    public void testInsert3(){
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        try {

            long start = System.currentTimeMillis();

            connection = JDBCUtils.getConnection();

            //设置不允许自动提交数据
            connection.setAutoCommit(false);

            String sql = "insert into goods(name)values(?)";

            preparedStatement = connection.prepareStatement(sql);

            for (int i = 0; i < 2000000; i++) {
                preparedStatement.setObject(1,"name_" + i);

                //1、暂时缓存sql,缓存一定数量之后再与数据库交互,进行插入
                preparedStatement.addBatch();

                if(i % 500 == 0){       //缓存500个sql,执行一次数据库插入的交互

                    //2、执行batch
                    preparedStatement.executeBatch();

                    //3、清空batch
                    preparedStatement.clearBatch();
                }

            }

            //统一提交数据
            connection.commit();

            long end = System.currentTimeMillis();

            System.out.println("花费的时间为:" + (end - start));

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.closeResource(connection,preparedStatement);
        }
    }
  • 2
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
你可以使用JDBC来批量插入数据到ClickHouse数据库。下面是一个简单的示例代码来演示如何使用JDBC批量插入数据: ```java import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; public class ClickHouseBatchInsert { public static void main(String[] args) { // JDBC连接信息 String url = "jdbc:clickhouse://localhost:8123/default"; String username = "your_username"; String password = "your_password"; // SQL插入语句 String sql = "INSERT INTO your_table (column1, column2, column3) VALUES (?, ?, ?)"; // 数据集 Object[][] data = { {"value1_1", "value1_2", "value1_3"}, {"value2_1", "value2_2", "value2_3"}, {"value3_1", "value3_2", "value3_3"} }; try (Connection conn = DriverManager.getConnection(url, username, password); PreparedStatement pstmt = conn.prepareStatement(sql)) { // 关闭自动提交 conn.setAutoCommit(false); // 批量插入数据 for (Object[] row : data) { for (int i = 0; i < row.length; i++) { pstmt.setObject(i + 1, row[i]); } pstmt.addBatch(); } // 执行批量插入 int[] result = pstmt.executeBatch(); // 提交事务 conn.commit(); System.out.println("成功插入 " + result.length + " 条数据"); } catch (SQLException e) { e.printStackTrace(); } } } ``` 在这个示例中,你需要将`url`、`username`和`password`替换为你实际的ClickHouse连接信息,将`your_table`替换为你要插入数据的目标表名。然后,根据你的数据集,调整`data`数组中的值和列数。 这个示例中使用了`PreparedStatement`来执行预编译的SQL语句,并使用`addBatch()`方法将批量插入的每一行添加到批处理中。最后,通过调用`executeBatch()`方法执行批处理操作,并使用`commit()`方法提交事务。 这样,你就可以使用JDBC批量插入数据到ClickHouse数据库了。希望对你有所帮助!如果有任何问题,请随时提问。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值