Get Number of Rows returned by ResultSet in Java

前端 未结 14 1181
挽巷
挽巷 2020-11-29 20:35

I have used a ResultSet that returns certain number of rows. My code is something like this:

ResultSet res = getData();
if(!res.next())
{
    Sy         


        
相关标签:
14条回答
  • 2020-11-29 21:05

    Another way to differentiate between 0 rows or some rows from a ResultSet:

    ResultSet res = getData();
    
    if(!res.isBeforeFirst()){          //res.isBeforeFirst() is true if the cursor
                                       //is before the first row.  If res contains
                                       //no rows, rs.isBeforeFirst() is false.
    
        System.out.println("0 rows");
    }
    else{
        while(res.next()){
            // code to display the rows in the table.
        }
    }
    

    If you must know the number of rows given a ResultSet, here is a method to get it:

    public int getRows(ResultSet res){
        int totalRows = 0;
        try {
            res.last();
            totalRows = res.getRow();
            res.beforeFirst();
        } 
        catch(Exception ex)  {
            return 0;
        }
        return totalRows ;    
    }
    
    0 讨论(0)
  • 2020-11-29 21:05

    You could count with sql and retrieve the answer from the resultset like so:

    Statment stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, 
                                         ResultSet.CONCUR_READ_ONLY);
    ResultSet ct = stmt.executeQuery("SELECT COUNT(*) FROM [table_name]");
    if(ct.next()){
       td.setTotalNumRows(ct.getInt(1));
    }
    

    Here I'm counting everything but you can easily modify the SQL to count based on a criteria.

    0 讨论(0)
提交回复
热议问题