When we perform a database query to return a resultset, in many cases we need to know the size of the resultset, which is the number of rows and columns. We know that the number of columns can be easily obtained by Resultset.getmetadata (). getColumnCount (), however, the Java API does not provide an interface to directly access the number of resultSet rows.
This time, there are three ways to solve:
1. Use the SELECT Count statement instead, and then get the results directly from the resultset:
Double-click the code to select all
1 2 3 4 5 6 7 8 9 |
try {Statement Statement = connection.createstatement (); ResultSet ResultSet = Statement.executequery ("SELECT count (*) as ROWCOUNT from TableName"); Resultset.next (); int rowcount = Resultset.getint ("rowcount"); catch (Exception e) {//Todo:handle Exception e.printstacktrace ();} |
However, we perform database queries not only to know the number of rows of the result, but also to use the query results. If you use this method, you will need to execute a SELECT statement again in order to get the desired result set, so that a more database query, greatly reduce the execution speed.
2. Traverse resultset and record the number of rows with a variable. The code is as follows:
Double-click Code
1 2 3 4 5 6 7 8 9 |
int count = 0; try { while (Resultset.next ()) { count = count + 1; } catch (SQLException E1) { |