我试图从executeBatch()事务中检索生成的键,但我只获取要添加的最后一个键.
这是我的代码:
PreparedStatement ps_insert = conn.prepareStatement(insertQuery,PreparedStatement.RETURN_GENERATED_KEYS); for (int i = 0 ; i < adding_dates.length ; i++){ ps_insert.setInt(1,Integer.parseInt(consultant_id)); ps_insert.setDate(2,adding_dates[i]); ps_insert.setInt(3,Integer.parseInt(room_id)); ps_insert.addBatch(); } ps_insert.executeBatch(); ResultSet rs = ps_insert.getGeneratedKeys(); //<-- Only the last key retrieved conn.commit();
我究竟做错了什么?
编辑:抱歉没有提到我在嵌入模式下使用H2(http://www.h2database.com/html/main.html)数据库.
解决方法
根据H2
jdbc driver javadocs,这是正常行为:
Return a result set that contains the last generated auto-increment key for this connection,if there was one. If no key was generated by the last modification statement,then an empty result set is returned. The returned result set only contains the data for the very last row.