Take the 2-minute tour ×

This question already has an answer here:

How can I find that the ResultSet, that I have got by querying a database, is empty or not?

share|improve this question
add comment

marked as duplicate by dimo414, greg-449, Frank van Puffelen, ArtB, Alex K Nov 4 '13 at 17:53


6 Answers

up vote 13 down vote accepted

Immediately after your execute statement you can have an if statement. For example

ResultSet rs = statement.execute();
if (!rs.next()){
//ResultSet is empty
share|improve this answer
add comment

Definitely this gives good solution,

ResultSet rs = stmt.execute("SQL QUERY");
// With the above statement you will not have a null ResultSet 'rs'.
// In case, if any exception occurs then next line of code won't execute.
// So, no problem if I won't check rs as null.

if (rs.next()) {
    do {
      // Logic to retrieve the data from the resultset.
      // eg: rs.getString("abc");
    } while(rs.next());
} else {
    // No data
share|improve this answer
add comment

Do this using rs.next():

while (rs.next())

If the result set is empty, the code inside the loop won't execute.

share|improve this answer
add comment

If you use rs.next() you will move the cursor, than you should to move first() why don't check using first() directly?

    public void fetchData(ResultSet res, JTable table) throws SQLException{     
    ResultSetMetaData metaData = res.getMetaData();
    int fieldsCount = metaData.getColumnCount();
    for (int i = 1; i <= fieldsCount; i++)
        ((DefaultTableModel) table.getModel()).addColumn(metaData.getColumnLabel(i));
    if (!res.first())
        JOptionPane.showMessageDialog(rootPane, "no data!");
        do {
            Vector<Object> v = new Vector<Object>();
            ((DefaultTableModel) table.getModel()).addRow(v);
        } while (res.next());
share|improve this answer
I agree. I added my code below (could not include code with the comment). –  Santosh Tiwari Jul 1 '11 at 14:06
add comment

Calculates the size of the java.sql.ResultSet:

int size =0;
if (rs != null) {
    size = rs.getRow();


share|improve this answer
As far as I know, that is a bad idea... first of all, you need to ensure that the result can move backwards, second of all, you take a performance hit when doing that. Much quicker to just use a forward only result set, and use a while loop (like has already been suggested by others here) –  user85116 Apr 19 '10 at 14:21
Agree... I voted up the accepted answer, which answers the question much more directly. –  Dolph Apr 20 '10 at 1:49
add comment
if (rs == null || !rs.first()) {
} else {
    //not empty

Note that after this method call, if the resultset is not empty, it is at the beginning.

share|improve this answer
This way more safe, I thought. –  Kachwahed Sep 4 '11 at 18:13
ResultSet is never null. –  red1ynx Dec 28 '11 at 7:45
add comment
