Mr Asker
Mr Asker

Reputation: 2380

Get the number of rows from ResultSet

I am trying to get the number in ResultSet that I am getting from my query as in the code below. The query retrieves the number 5. How can I get this number from ResultSet?

Code:

String sql_count_stop = "select count(*) FROM behaviour where  mac = ? ";
PreparedStatement preparedCount = con.prepareStatement(sql_count_stop);
preparedCount.setString(1, macD);
ResultSet rsCount = preparedCount.executeQuery();
while(rsCount.next()){

}

Upvotes: 1

Views: 115

Answers (3)

apgp88
apgp88

Reputation: 995

You can modify your query to

"SELECT count(*) AS totalCount FROM behaviour WHERE mac = ? ";

and then use,

macId= rsCount.getInt("totalCount");

Upvotes: 3

dave_thompson_085
dave_thompson_085

Reputation: 39010

Or use position rsCount.getInt(1) and you don't need a column alias.

Also since there will be only one row, if(rsCount.next()) is just as good as while, and in my opinion more clearly shows this logic will only execute once.

Upvotes: 1

Oleksii Vynnychenko
Oleksii Vynnychenko

Reputation: 320

You can modify you SQL statement to: (added AS 'countMacs')

select count(*) as 'countMacs' FROM behaviour where  mac = ? 

Then get a value

while(rsCount.next()){
  int count = rsCount.getInt("countMacs");
}

Upvotes: 0

Related Questions