I’m trying to write a function that updates 2 tables in my database. I’m getting an error which i think is caused by calling next() on a resultset that has no more rows in the set.
I was thinking an if condition on hasNext() would fix this but it’s not available to the result set…
The error i’m getting is ‘No operations allowed after statement closed.’
private void updateDatabase() throws Exception {
Connection conn = getConnection();
PreparedStatement updateMovieStmt = conn.prepareStatement("INSERT INTO movies VALUES(null,?,null,null,null)", Statement.RETURN_GENERATED_KEYS);
PreparedStatement updateVideoStmt = conn.prepareStatement("INSERT INTO video_files VALUES(null,null,null,?,?)", Statement.RETURN_GENERATED_KEYS);
try {
for (Movie localMovie : getLocalMovies()) {
// fetch a local movie{
boolean newMovie = true;
for (Movie dbMovie : getDatabaseMovies(conn)) {
newMovie = true;
Pattern p = Pattern.compile(localMovie.getTitlePattern(), Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(dbMovie.getTitle());
// if it's already in the database not new movie... but is
// is it a new video rip????????????;
if (m.find()) {
System.out.println("DB movie: " + dbMovie.getTitle() + " matches localpattern of: " + localMovie.getTitlePattern());
newMovie = false;
break;
}
}
if (newMovie == true && localMovie.getTitle() != null) {
updateMovieStmt.setString(1, localMovie.getTitle());
updateMovieStmt.executeUpdate();
// get new movie id and put into new video row
ResultSet rs = updateMovieStmt.getGeneratedKeys();
if (rs.next()) {
updateVideoStmt.setBytes(1, localMovie.getHash());
updateVideoStmt.setInt(2, rs.getInt(1));
updateVideoStmt.executeUpdate();
}
}
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
updateMovieStmt.close();
updateVideoStmt.close();
conn.close();
}
}
If you’re not using batches (
addBatch()/executeBatch()), nor clearing the parameters (clearParameters()), then you should be creating the statements inside the loop, not outside the loop.Move the both
conn.prepareStatement()lines into theif (newMovie == true && localMovie.getTitle() != null)block, preferably refactored in separate methods. Your current method is doing way too much.