问题描述
我想使用PreparedStatement
INSERT
多行:
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();
这时,当我期望获得每个INSERT
生成的PK时,我得到以下SQLServerException
:
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.
我希望对每个执行的插入操作都获得一个ResultSet一行,因此我可以生成每个PK.
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?
推荐答案
批处理执行中对getGeneratedKeys()
的支持是根据JDBC规范定义的实现. SQL Server驱动程序很可能不支持它执行批处理.
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.
我试图在Microsoft网站上寻找明确的声明,但找不到它. MSDN上的这个旧版(2007年)论坛帖子确实指出它不受支持: http://social.msdn.microsoft.com/Forums/en-US/sqldataaccess/thread/6cbf5eea-e5b9-4519-8e86-f4b65ce3f8e1
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
这篇关于PreparedStatement.executeBatch()之后的getGeneratedKeys()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!