[英]How to get generated keys using SimpleJdbcInsert and executeBatch with MYSQL JDBC driver?
[英]How to get generated keys by executeBatch without ArrayIndexOutOfBoundsException?
下面的方法我想同時插入多條記錄。
public void insert() {
try {
this.connection.setAutoCommit(false);
PreparedStatement ps = this.connection.prepareStatement(
"INSERT INTO COMPANY (NAME,Address) Values (?,?)", new String[]{"ID"});
ps.setString(1, "X01");
ps.setString(2, "Address1");
ps.addBatch();
ps.setString(1, "Y01");
ps.setString(2, "Address2");
ps.addBatch();
//EXCEPTION OCCURS HERE
int[] numUpdates = ps.executeBatch();
for (int i = 0; i < numUpdates.length; i++) {
System.out.println("Execution " + i +
"successful: " + numUpdates[i] + " rows inserted");
}
ResultSet resultSet =
(ps).getGeneratedKeys();
while (resultSet.next()) {
String deptNoKey = resultSet.getString(1);
System.out.println("Automatically generated key value = "
+ deptNoKey);
}
} catch (BatchUpdateException b) {
// process BatchUpdateException
} catch (SQLException e) {
e.printStackTrace();
}
}
在這一點上,當我希望為每個 INSERT 生成 PK 時,我得到了這個異常
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 22 at oracle.jdbc.driver.T4CNumberAccessor.unmarshalOneRow(T4CNumberAccessor.java:250) at oracle.jdbc.driver.T4C8Oall.receive(T4C8Oall.java:754) at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:216) at oracle.jdbc.driver.T4CPreparedStatement.executeForRows(T4CPreparedStatement.java:1250) at oracle.jdbc.driver.OraclePreparedStatement.executeForRowsWithTimeout(OraclePreparedStatement.java:14264) at oracle.jdbc.driver.OraclePreparedStatement.executeBatch(OraclePreparedStatement.java:14379) at oracle.jdbc.driver.OracleStatementWrapper.executeBatch(OracleStatementWrapper.java:589) at dbpro.SqlHelper.insert2(SqlHelper.java:988) at dbpro.SqlHelper.main(SqlHelper.java:1023) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:483) at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)
異常之后:在表 COMPANY 中,正確添加了兩條記錄,但我希望得到一個 ResultSet ,每次執行插入時都有一行,因此我可以生成每個 PK。
這似乎是 Windows 上的 Oracle、驅動程序 JAR ojdbc6.jar 或(知道 Oracle)兩者中的錯誤。
您提供的代碼沒有重大問題。 它應該可以工作,盡管當我運行它時,每次插入的行數返回為 -2(= Statement.SUCCESS_NO_INFO
),因此您最好忽略這些數字。
您的代碼在 Linux 上使用 Oracle 11g XE 11.2.0.2.0 和四個版本的 Oracle JDBC 驅動程序 JAR 運行良好。 但是,如果我在具有相同版本的 Oracle XE 和 ojdbc6.jar 的 Windows 10 上運行它,它會失敗並出現與您相同的 ArrayIndexOutOfBoundsException。 如果我使用 ojdbc7.jar 而不是 ojdbc6.jar,問題就會消失。
因此,我建議將 ojdbc6.jar 替換為 ojdbc7.jar,您可以從這里下載。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.