getGeneratedKeys() after PreparedStatement.executeBatch()

[亡魂溺海] 提交于 2019-11-30 16:51:39

问题


I want to INSERT several rows using a PreparedStatement:

ps = con.prepareStatement(query,PreparedStatement.RETURN_GENERATED_KEYS);

for(Element e:listOfElements){
    ps.setString(1,this.col_val_1);
    ps.setString(2,this.col_val_2);
    ps.setInt(3,this.col_val_3);

    ps.addBatch();
}

ps.executeBatch();
ResultSet rs = ps.getGeneratedKeys();

At this point, whent I expect to get the PK's generated for each INSERT, I get this SQLServerException:

com.microsoft.sqlserver.jdbc.SQLServerException: The statement must be executed before any results can be obtained.

I expected to get a ResultSet with one row for each insert performed, so I could get each PK generated.

Am I expecting wrong? Am I doing something wrong? Can it be done in a different way using batch execution?


回答1:


Support for getGeneratedKeys() on batch execution is implementation defined according to the JDBC spec. Most likely the SQL Server driver does not support it for batch execution.

I tried to look for an explicit statement on the Microsoft site, but couldn't find it. This old (2007) forum post on MSDN does state that it isn't supported: http://social.msdn.microsoft.com/Forums/en-US/sqldataaccess/thread/6cbf5eea-e5b9-4519-8e86-f4b65ce3f8e1



来源:https://stackoverflow.com/questions/13641832/getgeneratedkeys-after-preparedstatement-executebatch

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!