我使用preparedStatements和ExecuteBatch()将483个对象添加到数据库中。 当我运行此代码时,所有对象都正确地添加到数据库中,但一段时间后程序抛出:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 484
at com.mysql.jdbc.StatementImpl.processMultiCountsAndKeys(StatementImpl.java:1417)
at com.mysql.jdbc.PreparedStatement.executePreparedBatchAsMultiStatement(PreparedStatement.java:1515)
at com.mysql.jdbc.PreparedStatement.executeBatch(PreparedStatement.java:1389)
at model.database.SQLCommand.insertMeasurements(SQLCommand.java:110)
at model.database.SQLCommand.addDatasetToDb(SQLCommand.java:31)
at tests.readText.main(readText.java:35)
这是我的代码:
private static List<Long> insertMeasurements(List<Measurement> measurements, long did) throws SQLException {
conn.setAutoCommit(false);
List<Long> mids = new ArrayList<Long>();
String sql = "INSERT INTO doses (CPS, ground, total) VALUES (?, ?, ?);" + " " +
"INSERT INTO places (x, y, z, speed) VALUES (?, ?, ?, ?);" + " " +
"INSERT INTO measurements (time, place, note, dose, id_dataset) VALUES (?, (SELECT MAX(ID) FROM places), ?, (SELECT MAX(ID) FROM doses), ?)";
try (
PreparedStatement ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
) {
for(Measurement measurement: measurements) {
ps.clearParameters();
double cps = measurement.getDose().getCps();
double ground = measurement.getDose().getGround();
double total = measurement.getDose().getTotal();
ps.setDouble(1, cps);
ps.setDouble(2, ground);
ps.setDouble(3, total);
double x = measurement.getPlace().getX();
double y = measurement.getPlace().getY();
double z = measurement.getPlace().getZ();
double speed = measurement.getPlace().getSpeed();
ps.setDouble(4, x);
ps.setDouble(5, y);
ps.setDouble(6, z);
ps.setDouble(7, speed);
String time = measurement.getDate().toString();
String note = measurement.getNote().toString();
ps.setString(8, time);
ps.setString(9, note);
ps.setObject(10, did);
ps.addBatch();
}
ps.executeBatch();
conn.commit();
ResultSet rs = ps.getGeneratedKeys();
while (rs.next()) {
long id = rs.getLong(1);
mids.add(id);
}
} catch (SQLException e) {
throw new SQLException("Can't add the measurement."+e.toString()+"\n" );
}
return mids;
}