文档

如何高效地写入数据

更新时间:

本文介绍通过JDBC向时序引擎中写入数据的方法。

基于JDBC开发高效数据写入的应用

对于使用JDBC进行应用开发的场景,为了达到高效数据写入的目的,推荐使用JDBC中的PreparedStatement实现INSERT语句的批量写入。具体步骤如下:

  1. 使用JDBC创建Connection对象。

    通过JDBC建立连接的方法,详细可参见通过JDBC Driver连接使用(推荐)

  2. 创建PreparedStatement对象并指定带参数的INSERT语句。

    以"如何为时序数据建表"章节中介绍的示例为基础,创建PreparedStatement的方法如下所示:

        StringBuilder builder = new StringBuilder();
        builder.append("INSERT INTO aqm (city, district, id, time, pm2_5, pm10, so2, no2) ");
        builder.append("VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
    
        PreparedStatement preparedStmt = connection.prepareStatement(builder.toString());
  3. PreparedStatement对象进行批量的输入参数绑定,并实际执行写入。

    对于上一步的INSERT语句,绑参的示例代码如下:

        for (int i = 0; i < batchSize; i++) {
            // 按INSERT语句中的列参数指定顺序依次绑参
            // 下述代码中的 city, district, id, ts, pm25等都是用于绑参的局部变量
            preparedStmt.setString(1, city);
            preparedStmt.setString(2, district);
            preparedStmt.setString(3, id);
            preparedStmt.setTimestamp(4, ts);
            preparedStmt.setDouble(5, pm25);
            preparedStmt.setDouble(6, pm10);
            preparedStmt.setDouble(7, so2);
            preparedStmt.setDouble(8, no2);
            
            // 加入批次
            preparedStmt.addBatch();
        }
    
        // 执行一个批次的写入
        int[] results = preparedStmt.executeBatch();
    
        // 从results中查询实际写入的数据记录数。以下略
    }
说明

  • 时序引擎的JDBC中的PreparedStatement只支持无命名参数(即通过占位符“?”指定参数),因此在实际调用PreparedStatement的绑参API时,需要确保setXXX()方法中指定的参数index所对应的参数值与INSERT语句中占位符所对应列一致。

  • PreparedStatement在执行executeBatch()前绑定的参数批次并不是越多越好,其性能表现往往与表定义相关。根据实际测试的结果,如果表定义中仅有1个Field,并且TAG列的个数不超过5个时,PreparedStatement执行的一个批次的个数为5000(即上述代码示例中的batchSize变量大小)性能最优。

  • 本页导读 (1)
文档反馈