Get Number of Rows returned by ResultSet in Java

前端 未结 14 1180
挽巷
挽巷 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 20:53
    Statement st = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
    ResultSet rs=st.executeQuery("select * from emp where deptno=31");
    rs.last();
    System.out.println("NoOfRows: "+rs.getRow());
    

    first line of code says that we can move anywhere in the resultset( either to first row or last row or before first row without the need to traverse row by row starting from first row which is time taking).second line of code fetches the records matching the query here i am assuming (25 records), third line of code moves cursor to last row and final line of code gets the current row number which is 25 in my case. if there are no records, rs.last returns 0 and getrow moves cursor to before first row hence returning negative value indicates no records in db

    0 讨论(0)
  • 2020-11-29 20:54

    res.next() method will take the pointer to the next row. and in your code you are using it twice, first for the if condition (cursor moves to first row) then for while condition (cursor moves to second row).

    So when you access your results, it starts from second row. So shows one row less in results.

    you can try this :

    if(!res.next()){ 
        System.out.println("No Data Found");  
    }
    else{
        do{
           //your code
        } 
        while(res.next());
    }
    
    0 讨论(0)
  • 2020-11-29 20:55

    In my case, I needed to get the total rows from a ResultSet and also access the ResultSet values ​​if the total rows did not reach the limit of an XLS file.

    For that, I had to make two adjustments to my code:

    1) Change in object construction PreparedStatement

    A default ResultSet object has a cursor that moves forward only. Thus, you can iterate through it only once and only from the first row to the last row. It is possible to produce ResultSet objects that are scrollable. The following code fragment illustrates how to make a result set that is scrollable and insensitive to updates by others.

    PreparedStatement ps = connection.prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE, 
    ResultSet.CONCUR_READ_ONLY);
    

    2) Get total rows. The following code fragment illustrates how:

    ResultSet rs = ps.executeQuery();
    rs.last();
    int totalRowsResult = rs.getRow();
    

    PS: If the number of records of the query result is too large, you may run out of memory on the Java server by getting an exception: java.lang.OutOfMemoryError: Java heap space. This exception will occur when executing the rs.last () method

    3) Access again the ResultSet and you don't get the message: exhaused result set. So, vou need reset the result set to the top, using rs.first() or rs.absolute(1). The following code fragment illustrates how:

    rs.first();
    System.out.println(rs.getString(1));
    
    0 讨论(0)
  • 2020-11-29 20:57

    You could use a do ... while loop instead of a while loop, so that rs.next() is called after the loop is executed, like this:

    if (!rs.next()) {                            //if rs.next() returns false
                                                 //then there are no rows.
        System.out.println("No records found");
    
    }
    else {
        do {
            // Get data from the current row and use it
        } while (rs.next());
    }
    

    Or count the rows yourself as you're getting them:

    int count = 0;
    
    while (rs.next()) {
        ++count;
        // Get data from the current row and use it
    }
    
    if (count == 0) {
        System.out.println("No records found");
    }
    
    0 讨论(0)
  • 2020-11-29 20:57

    If your query is something like this SELECT Count(*) FROM tranbook, then do this rs.next(); System.out.println(rs.getInt("Count(*)"));

    0 讨论(0)
  • 2020-11-29 21:03

    You may think JDBC is a rich API and ResultSet has got so many methods then why not just a getCount() method? Well, For many databases e.g. Oracle, MySQL and SQL Server, ResultSet is a streaming API, this means that it does not load (or maybe even fetch) all the rows from the database server. By iterating to the end of the ResultSet you may add significantly to the time taken to execute in certain cases.

    Btw, if you have to there are a couple of ways to do it e.g. by using ResultSet.last() and ResultSet.getRow() method, that's not the best way to do it but it works if you absolutely need it.

    Though, getting the column count from a ResultSet is easy in Java. The JDBC API provides a ResultSetMetaData class which contains methods to return the number of columns returned by a query and hold by ResultSet.

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