Reputation: 328
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
?
Upvotes: 3
Views: 3651
Reputation: 8387
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);
Upvotes: 4
Reputation: 311448
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);
Upvotes: 6