JDBC ResultSet关闭语句

时间:2011-05-15 23:18:48

标签: java jdbc resultset

我正在尝试编写一个更新数据库中2个表的函数。我收到一个错误,我认为这是由在set中没有更多行的结果集上调用next()引起的。 我在想hasNext()上的if条件会解决这个问题,但结果集不可用...

我得到的错误是'语句关闭后不允许操作。'

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();
        }
    }

2 个答案:

答案 0 :(得分:1)

如果您没有使用批次(addBatch() / executeBatch()),也没有清除参数(clearParameters()),那么您应该在循环内创建语句,而不是在循环。

将两个conn.prepareStatement()行移动到if (newMovie == true && localMovie.getTitle() != null)块中,最好以单独的方法重构。你当前的方法做得太多了。

答案 1 :(得分:1)

  

每个连接只能有一个打开的语句。在同一连接上创建新语句后,将关闭先前创建的语句

对于resultSet,我们只能在每个语句中打开一个resultSet。通过连接,我们可以打开多个语句。