连接关闭后清除ResultSet。 SQLite的

时间:2018-09-14 15:54:13

标签: java sqlite java-8 connection resultset

这是我的代码

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

您猜到了,IF块始终为false。但是,当这段代码如下所示时:

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

一切正常。和IF块可以是真的。 我猜想在关闭连接时会重置ResultSet。为什么会发生这种情况以及如何防止这种情况发生?

0 个答案:

没有答案