[英]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.如您所料,IF 块始终为假。 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.并且 IF 块可以为真。 I guess the ResultSet resets when connection closing.我猜连接关闭时 ResultSet 会重置。 Why this happens and how I can prevent this?为什么会发生这种情况以及如何防止这种情况发生?
I figured out.我想通了。 The prepared statement must not be closed for saving ResultSet.不得为保存 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();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.