Java SQL异常:Closed Resultset:next,即使连接或结果集都没有关闭

时间:2018-04-28 22:40:16

标签: java oracle jdbc

基本上,我有以下方法可以从oracle表中获取id:

public Integer findByName(String name) throws SQLException {
    Connection con = Database.getConnection();
    try (Statement stmt = con.createStatement();
         ResultSet rs = stmt.getResultSet()) {
        stmt.executeQuery("select id from artists where name='" + name + "'");
        return rs.next() ? rs.getInt(1) : null;
    }
}

在Main方法中,我试着像这样测试它:

public static void main(String[] args)
    {
        try {
            ArtistController artists = new ArtistController();
            AlbumController albums = new AlbumController();


            artists.create("Radiohead", "United Kingdom");
            artists.create("Phoenix", "Romania");
            Database.commit();


            int radioheadId = artists.findByName("Radiohead");
            System.out.println(radioheadId);

            albums.create(radioheadId,"OK COMPUTER", 1977);
            albums.create(radioheadId, "Kid A", 2000);
            albums.create(radioheadId, "In Rainbows", 2007);

            Database.commit();


            Database.closeConnection();
        } catch (SQLException e) {
            System.err.println(e);
            Database.rollback();
        }
    }

我得到异常:java.sql.SQLException:Closed Resultset:next虽然你可以看到我在rs之前都没有关闭连接或语句而且我不明白为什么

1 个答案:

答案 0 :(得分:1)

try-with-resources close ResultSet,但这不是真正的问题。您需要在执行}之前设置Statement (并且更喜欢PreparedStatement并绑定参数)。像,

public Integer findByName(String name) throws SQLException {
    String sql = "select id from artists where name=?";
    Connection con = Database.getConnection();
    try (PreparedStatement stmt = con.prepareStatement(sql)) {
        stmt.setString(1, name);
        try (ResultSet rs = stmt.executeQuery()) {
            return rs.next() ? rs.getInt(1) : null;
        }
    }
}