3

I am trying to perform an SQL query to see how many records there are in my table. The SQL that I'm using for this is SELECT COUNT(*) FROM myTable; The query is then being executed and stored in a ResultSet.

int recordNumber = 0;
    String sqlString = "SELECT COUNT(*) FROM myTable;";
    try {
        ResultSet resultSet = stmt.executeQuery(sqlString);
        resultSet.next();
        recordNumber = Integer.parseInt(rst);
    } catch (Exception e) {}

My questions is how do I get the number of records out of the ResultSet?

2 Answers 2

6

A ResultSet has a series of getXYZ(int) methods to retrieve columns from it by their relative index and corresponding getXYZ(String) methods to retrieve those columns by their alias. In your case, using the index variant getInt(int) would be the easiest:

recordNumber = resultSet.getInt(1);
Sign up to request clarification or add additional context in comments.

Comments

4

Try to use this query adding a name count to column like this :

  String sqlString = "SELECT COUNT(*) as count FROM myTable";

And then with getInt(..) you can retrieve the value like this:

    if(resultSet.next())
     recordNumber = resultSet.getInt(count);// with name of column

Or using the index of column like this:

    if(resultSet.next())
     recordNumber = resultSet.getInt(1);

1 Comment

why you call Integer.parseInt where ResultSet#getInt already returns int?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.