H
H
Hello America2014-05-21 08:18:40
MySQL
Hello America, 2014-05-21 08:18:40

Get number of rows by MySQL/Java condition

Everything is somehow problematic, is there any solution? What I don't do doesn't work. I tried different options, in particular the following code:

try{
        String query = "Select parent_id FROM chat_rooms WHERE parent_id=2";
      Statement stmt = (Statement) this.connection.createStatement();

      ResultSet rs = stmt.executeQuery(query);

                        rs.last();
                        int count= rs.getRow();//количество строк
      //while (rs.next()) {
                           // count++;
      //} // end while
                        //return count;
      }// end try
       catch (SQLException e) {
      e.printStackTrace();
      // Could not connect to the database
                        System.out.println("Could not connect to the database");
    }

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexey Cheremisin, 2014-05-21
@leahch

And actually the request is processed? Have you tried running it directly? Tried to get the number of records via "SELECT count(parent_id) FROM chat_rooms WHERE parent_id=2"

M
Malah, 2014-05-21
@Malah

1) The number of rows that satisfies the condition is searched for by a query like this SELECT count(*) FROM chat_rooms WHERE parent_id=
2 it is possible to work through interface ResultSet. In the case of the query from point 1, the result will be a set of exactly one row, with one column, which will contain the result of the count (*) function - the number of rows from the chat_rooms table with parent_id=2.
3) You can get the result like this:

ResultSet rs = stmt.executeQuery(query);
int count = 0;
if(rs.next()) {
    count = rs.getInt(1);
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question