Mr Asker
Mr Asker

Reputation: 2380

Get the number of the affected rows

I am trying to get the number of the affected records of this query SELECT mac, stop_name from behaviour where mac = ? with the use of the executeQuery. How can I get the number of the affected rows?

Code:

if (behaviourExist.next()) {
    PreparedStatement prepared = con
            .prepareStatement("SELECT mac, stop_name from behaviour where mac = ?");
    prepared.setString(1, macD);
    ResultSet rsBehav = prepared.executeQuery();
    ArrayList<String> stopNameList = new ArrayList<String>();
    while (rsBehav.next()) {
        //int numberOfRows = rsBehav.getInt(1);
        String stNa = rsBehav.getString("stop_name");
        if (stNa.equals(nameShortestDistance)) {
            stopNameList.add(stNa);

        }

    }
}

Upvotes: 0

Views: 125

Answers (3)

swifty
swifty

Reputation: 181

if (behaviourExist.next()) {
PreparedStatement prepared = con
        .prepareStatement("SELECT mac, stop_name from behaviour where mac = ?");
prepared.setString(1, macD);
ResultSet rsBehav = prepared.executeQuery();
ArrayList<String> stopNameList = new ArrayList<String>();
int numberOfRows = 0;
while (rsBehav.next()) {
    ++numberOfRows;
    String stNa = rsBehav.getString("stop_name");
    if (stNa.equals(nameShortestDistance)) {
        stopNameList.add(stNa);

    }
}
}

Here the variable numberOfRows will increment each time the loop runs which will give you the total number of rows in the resultSet.

Upvotes: 0

user4910279
user4910279

Reputation:

PreparedStatement prepared = con
        .prepareStatement(
         "SELECT (SELECT count(*) from where mac = ?),"
         " mac, stop_name from behaviour where mac = ?");
prepared.setString(1, macD);
prepared.setString(2, macD);
ResultSet rsBehav = prepared.executeQuery();
ArrayList<String> stopNameList = new ArrayList<String>();
while (rsBehav.next()) {
    int numberOfRows = rsBehav.getInt(1);
    String stNa = rsBehav.getString("stop_name");
    // ....

Upvotes: 0

barunsthakur
barunsthakur

Reputation: 1216

This is a read operation so it will not affect any row. If you want to get the number of row returned then you could do one of the below

  1. Use a counter variable and increment it in the loop while (rsBehav.next())

  2. Use a scrollable resultset

    PreparedStatement prepared = con.prepareStatement(
            "SELECT mac, stop_name from behaviour where mac = ?",
            ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
    ResultSet rsBehav = prepared.executeQuery();
    rsBehav.afterLast();
    int numRow = rsBehav.getRow();
    rsBehav.beforeFirst();
    

Here numRow will give you number or row returned,

Upvotes: 1

Related Questions