How to get generated keys from JDBC batch insert in Oracle?

后端 未结 2 688
孤独总比滥情好
孤独总比滥情好 2020-12-15 09:41

I am inserting many records using JDBC batch inserts. Is there any way to get the generated key for each record? Can I use ps.getGeneratedKeys() with batch ins

相关标签:
2条回答
  • 2020-12-15 10:22

    The JDBC 4.1 specification, section 13.6 Retrieving Auto Generated Values says:

    It is implementation-defined as to whether getGeneratedKeys will return generated values after invoking the executeBatch method.

    So you will need to check if your driver actually supports it for batch updates. As indicated in the answer by Philip O., retrieval of generated keys is not supported with batch updates as documented in Oracle 12 JDBC Standards Support:

    You cannot combine auto-generated keys with batch update.

    In any case if it is supported by your driver than your statement prepare should be changed to the code below to instruct the driver to retrieve generated keys:

    ps = con.prepareStatement(insert, Statement.RETURN_GENERATED_KEYS);
    

    Note: you may need to use one of the other generated keys prepare methods (prepareStatement(sql, columnIndexes) or prepareStatement(sql, columnNames)) as Oracle will return the ROW_ID with the method in my example.

    0 讨论(0)
  • 2020-12-15 10:31

    It appears that Oracle 12c does not support combining auto-generated keys with batch update according to the following page:

    http://docs.oracle.com/cd/E16655_01/java.121/e17657/jdbcvers.htm

    See the subsection labeled "Limitations" under the section "Retrieval of Auto-Generated Keys"

    0 讨论(0)
提交回复
热议问题