Ask Your Question
2

What is the method to retrieve the length of SQL results using Java?

asked 2021-05-05 11:00:00 +0000

devzero gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2022-10-14 00:00:00 +0000

scrum gravatar image

To retrieve the length (number of rows) of SQL results using Java, you can use the ResultSet.getRow() method. This method returns the current row number within the ResultSet. You can iterate through the ResultSet using a while loop to count the number of rows. Here's an example code snippet:

try {
    Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/mydatabase", "username", "password");
    Statement stmt = conn.createStatement();
    ResultSet rs = stmt.executeQuery("SELECT * FROM mytable");

    int rowCount = 0;
    while (rs.next()) {
        rowCount++;
    }

    System.out.println("Number of rows: " + rowCount);

    rs.close();
    stmt.close();
    conn.close();
} catch (SQLException e) {
    e.printStackTrace();
}

In this example, we create a connection to a MySQL database and execute a SELECT query to retrieve all rows from a table called "mytable". We then use a while loop to iterate through the ResultSet and increment a rowCount variable for each row. Finally, we print out the number of rows to the console.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-05-05 11:00:00 +0000

Seen: 11 times

Last updated: Oct 14 '22