0

I've got a problem with my Java plugin - when there's no results found it says that result set is empty. Could someone tell me how to detect if result set is empty?

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();
spongebob
  • 8,370
  • 15
  • 50
  • 83
Kamil Oczkowski
  • 125
  • 2
  • 9
  • What's the exact problem? How are you consuming the `ResultSet`? – Luiggi Mendoza Apr 06 '13 at 12:54
  • See: http://sscce.org/ and update your post to a more understandable question. – xQuare Apr 06 '13 at 12:57
  • Thats my code: 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"); – Kamil Oczkowski Apr 06 '13 at 12:58
  • And then i do that to get result rs = stmt.getResultSet(); – Kamil Oczkowski Apr 06 '13 at 12:58
  • The exception stack trace tells exactly where this exception is thrown. Post this stack trace, and the relevant code. – JB Nizet Apr 06 '13 at 13:30

1 Answers1

2

The standard approach is to attempt to get the next row using the next() method, and check if it returned false (meaning there is no next row, so it's empty). Like this:

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

It can be convenient to code a do...while loop:

if (!rs.next()) {
    // handle no rows found
} else {
    // process all rows
    do {
        // process row
    } while (rs.next());
}
Misa Lazovic
  • 2,805
  • 10
  • 32
  • 38
Bohemian
  • 412,405
  • 93
  • 575
  • 722