Home > Database > Mysql Tutorial > How to Efficiently Iterate Through a Java ResultSet and Retrieve Multiple Rows?

How to Efficiently Iterate Through a Java ResultSet and Retrieve Multiple Rows?

DDD
Release: 2024-12-21 18:16:15
Original
704 people have browsed it

How to Efficiently Iterate Through a Java ResultSet and Retrieve Multiple Rows?

Iterating Through a Result Set in Java

When working with a ResultSet object in Java, it is essential to iterate through its rows to retrieve the desired data. This question demonstrates how to extract one row of data, but more commonly multiple rows need to be extracted.

Solution to the problem

The following code demonstrates how to loop through the result set and use two different lists (sids and lids) to store the corresponding column values:

List<String> sids = new ArrayList<String>();
List<String> lids = new ArrayList<String>();

String query = "SELECT rlink_id, COUNT(*)"
             + "FROM dbo.Locate  "
             + "GROUP BY rlink_id ";

Statement stmt = yourconnection.createStatement();
try {
    ResultSet rs4 = stmt.executeQuery(query);

    while (rs4.next()) {
        sids.add(rs4.getString(1));
        lids.add(rs4.getString(2));
    }
} finally {
    stmt.close();
}

String[] show = sids.toArray(sids.size());
String[] actuate = lids.toArray(lids.size());
Copy after login

Code Description

  • The two lists sids and lids are initialized to store the corresponding columns the extracted value.
  • Creates a ResultSet object using the given query.
  • The while loop iterates through the result set, getting the values ​​of the two columns of each row and adding them to the list.
  • Finally, convert the list to an array to access the extracted data when needed.

Using this approach, you can efficiently iterate over the result set and use the extracted data as needed.

The above is the detailed content of How to Efficiently Iterate Through a Java ResultSet and Retrieve Multiple Rows?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template