Search code examples
javasqlitejava-8connectionresultset

ResultSet cleared after connection close. SQLite


Here is my code

public static void main(String[] args) throws SQLException {
    Long chatId = 432878720L;
    String what = "*";
    String from = "BtcUser";
    ResultSet rs = selectUser(what, from, chatId);
    if (rs.next()) {
        System.out.println("NEVER REACH");
    }
}

private static ResultSet selectUser(String what, String from, long chatId) throws SQLException {
    String sql = "SELECT "+what+" FROM "+from+" WHERE chatId = ?;";
    ResultSet rs;
    try (Connection con = DriverManager.getConnection(url);
         PreparedStatement pst = con.prepareStatement(sql)) {
        pst.setLong(1, chatId);
        rs = pst.executeQuery();
        return rs;
    }
}

As you guessed, the IF block is always false. But when this code make like this:

public static void main(String[] args) throws SQLException {
    Long chatId = 432878720L;
    String what = "*";
    String from = "BtcUser";
    String sql = "SELECT "+what+" FROM "+from+" WHERE chatId = ?;";
    ResultSet rs;
    try (Connection con = DriverManager.getConnection(url);
         PreparedStatement pst = con.prepareStatement(sql)) {
        pst.setLong(1, chatId);
        rs = pst.executeQuery();
        if (rs.next()) {
            System.out.println("HELLO");
        }
    }
}

Everything works. And IF block can be true. I guess the ResultSet resets when connection closing. Why this happens and how I can prevent this?


Solution

  • I figured out. The prepared statement must not be closed for saving ResultSet. So this works:

    public static void main(String[] args) throws SQLException {
        long chatId = 432878720L;
        String what = "*";
        String from = "BtcUser";
        ResultSet rs = f(what, from, chatId);
        if (rs.next()) {
            System.out.println("HELLO");
        }
    }
    
    private static ResultSet f(String what, String from, long chatId) throws SQLException {
        String sql = "SELECT "+what+" FROM "+from+" WHERE chatId = ?;";
        try (Connection con = DriverManager.getConnection(url)) {
            PreparedStatement pst = con.prepareStatement(sql);
            pst.setLong(1, chatId);
            return pst.executeQuery();
        }
    }