簡體   English   中英

連接關閉后 ResultSet 被清除。 SQLite

[英]ResultSet cleared after connection close. SQLite

這是我的代碼

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 塊始終為假。 但是當這段代碼像這樣:

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 會重置。 為什么會發生這種情況以及如何防止這種情況發生?

我想通了。 不得為保存 ResultSet 關閉准備好的語句。 所以這有效:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM