具有返回子句的JDBC批量插入

时间:2014-06-23 05:08:33

标签: oracle jdbc batch-insert

使用JDBC Batch Insert语句时,有没有办法在JAVA中使用return子句获取受影响行的值?我能够获得受影响的单行所需的值。但不是所有批量插入?

代码:

try {
    String query = "INSERT INTO temp ( "
                 + "org_node_id, org_node_category_id,  org_node_name, "
                 + "customer_id, created_by, created_date_time, "
                 + "updated_date_time, activation_Status )"
                 + " VALUES (seq_org_node_id.nextval,  11527,  'Abcd',  9756,  1,  sysdate,   sysdate,   'AC')"
    +" returning org_node_id, org_node_name INTO ?, ?";

    con = DBUtils.getOASConnection();

    OraclePreparedStatement ps = (OraclePreparedStatement) con.prepareStatement(query);
    ps.registerReturnParameter(1, Types.INTEGER);
    ps.registerReturnParameter(2, Types.VARCHAR);
    ps.execute();

    ResultSet rs = ps.getReturnResultSet();
    rs.next();

    System.out.println("Org ID : "+ rs.getInt(1));
    System.out.println("Org Name : "+ rs.getString(2));

} catch (SQLException e) {
  e.printStackTrace();
}

1 个答案:

答案 0 :(得分:0)

ojdbc不支持批量处理INSERT .. RETURNING语句,但bulk insertion可以使用PL/SQL's FORALL命令。

给出一张表......

CREATE TABLE x (
  i INT GENERATED ALWAYS AS IDENTITY PRIMARY KEY, 
  j VARCHAR2(50), 
  k DATE DEFAULT SYSDATE
);

......和类型......

CREATE TYPE t_i AS TABLE OF NUMBER(38);
/
CREATE TYPE t_j AS TABLE OF VARCHAR2(50);
/
CREATE TYPE t_k AS TABLE OF DATE;
/

...您可以通过running a bulk insert, and bulk collecting the results (as I've shown also in this blog post)解决此限制:

try (Connection con = DriverManager.getConnection(url, props);
    CallableStatement c = con.prepareCall(
        "DECLARE "
      + "  v_j t_j := ?; "
      + "BEGIN "
      + "  FORALL j IN 1 .. v_j.COUNT "
      + "    INSERT INTO x (j) VALUES (v_j(j)) "
      + "    RETURNING i, j, k "
      + "    BULK COLLECT INTO ?, ?, ?; "
      + "END;")) {

    // Bind input and output arrays
    c.setArray(1, ((OracleConnection) con).createARRAY(
        "T_J", new String[] { "a", "b", "c" })
    );
    c.registerOutParameter(2, Types.ARRAY, "T_I");
    c.registerOutParameter(3, Types.ARRAY, "T_J");
    c.registerOutParameter(4, Types.ARRAY, "T_K");

    // Execute, fetch, and display output arrays
    c.execute();
    Object[] i = (Object[]) c.getArray(2).getArray();
    Object[] j = (Object[]) c.getArray(3).getArray();
    Object[] k = (Object[]) c.getArray(4).getArray();

    System.out.println(Arrays.asList(i));
    System.out.println(Arrays.asList(j));
    System.out.println(Arrays.asList(k));
}

结果是:

[1, 2, 3]
[a, b, c]
[2018-05-02 10:40:34.0, 2018-05-02 10:40:34.0, 2018-05-02 10:40:34.0]