In general, I work with MySQL via JDBC. I make a request to the database:

SELECT * FROM Leters LIMIT 0, 500 

At the output, I naturally get the ResulSet object, but how do I know how many rows returned the request. The getFetchSize () and getFetchDirection () methods return something wrong. Maybe somehow through other objects this is done?

    4 answers 4

    Hm The provided out-of-the-box method, as I understand it, is not. You have to do something like:

     public static int getResultSetRowCount(ResultSet resultSet) { int size = 0; try { resultSet.last(); size = resultSet.getRow(); resultSet.beforeFirst(); } catch(SQLException ex) { return 0; } return size; } 

    Sad :(

      Came up with 2 more ways

      1. ResultSet resultSet = stmt.executeQuery("SELECT * FROM my_table");
        resultSet.last();
        int rowCount = resultSet.getRow();

      2. SELECT COUNT(*) FROM

      • Well, the first method is a simplified version of my method))) One-liner, so to speak. The second way I tried, did not work. It gives the error "Before open ResultSet", although everything seems to be thinking. - Shamanis
      • I also thought of a variant, the usual i ++ in a loop. and with 2m there should be no problems, it's a normal query that returns the number of rows - Gorets
       while (rs.next()){ i++; } 
      • Well, this is the simplest solution))) it takes too much time, and this is unacceptable)) - Shamanis
      • I do not think that it is particularly different from the previous ones, it is possible, in some cases it is better, for example, when you need this result “not immediately”, but you will bypass ResultSet anyway, you can collect the size at the same time =) - Gorets
      • the fact of the matter is that I need it right away :) oh, okay, I’m learning the method itself ... Actually, I’m struck by the absence of the sometimes elementary methods it would seem))) - Shamanis
      • And how do you imagine the physical realization of what you want? The DBMS executes the SQL query and, in general, does not know the size of the result. The data received during execution is immediately sent to the client. “Thank” the creators of SQL who did not (apparently deliberately) control the physical aspects of DBMS functioning at the level of SQL queries. - avp
      • well I do not know, ResulSet - object? Does he already have a certain size? - Gorets

      DatabaseMetaData may help (see JavaDoc).

      • although I prefer the answer @Chupa - Viacheslav
      • This is column information. - Shamanis