7

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

代码 :

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();
}
4

1 回答 1

0

INSERT .. RETURNINGojdbc 不支持批处理语句,但可以使用PL/SQL 的命令进行批量插入。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;
/

...您可以通过运行批量插入和批量收集结果(正如我在此博客文章中所展示的那样)来解决此限制,如下所示:

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]
于 2018-05-02T08:52:33.270 回答