在使用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,'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(); }
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,"T_J"); c.registerOutParameter(4,"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]