0

我的 Java 插件有问题 - 当没有找到结果时,它说结果集是空的。有人能告诉我如何检测结果集是否为空吗?

String url = "jdbc:mysql://" + host + ":" + port + "/" + database + "";

Connection conn = DriverManager.getConnection(url, username, password);
Statement stmt = conn.createStatement();

ResultSet rs;
String p = pp.getName();
rs = stmt.executeQuery("SELECT * FROM " + table + " WHERE username='"
        + p + "' AND recieved=0 ORDER BY id DESC");
rs = stmt.getResultSet();
4

1 回答 1

2

标准方法是尝试使用该next()方法获取下一行,并检查它是否返回false(意味着没有下一行,所以它是空的)。像这样:

ResultSet rs;
// run query on database
if (!rs.next()) {
    // no row(s) found from database
} else {
    // row(s) found from database OK
}

do...while编写一个循环可以很方便:

if (!rs.next()) {
    // handle no rows found
} else {
    // process all rows
    do {
        // process row
    } while (rs.next());
}
于 2013-04-06T13:35:37.070 回答