How to get the number of rows and columns for resultset

Source: Internet
Author: User
Tags rowcount

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) {    

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.