Home >Database >Mysql Tutorial >How to Iterate Through a Java ResultSet and Extract Data?

How to Iterate Through a Java ResultSet and Extract Data?

Linda Hamilton
Linda HamiltonOriginal
2024-12-29 16:23:14599browse

How to Iterate Through a Java ResultSet and Extract Data?

Java: Iterating Through a Result Set

In Java, extracting data from a database into a ResultSet is a common task. Consider a query that retrieves the rlink_id and count of occurrences from the dbo.Locate table, grouped by rlink_id. The table contains the following data:

Sid Lid
3 2
4 4
7 3
9 1

To extract and process this data, it's necessary to loop through the ResultSet. The following Java code demonstrates how to achieve this:

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

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

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

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

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

In this code:

  1. Two ArrayLists, sids and lids, are initialized to store the rlink_id and count values, respectively.
  2. The query string represents the SQL query that retrieves the data.
  3. A Statement object is created and used to execute the query.
  4. The executeQuery method returns a ResultSet.
  5. The while loop iterates through the ResultSet, extracting the rlink_id and count values into the ArrayLists.
  6. After processing all rows, the ArrayLists are converted into String arrays for further use in your application.

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

Statement:
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