jasim
jasim

Reputation: 459

how to add values from a MySQL result-set while loop in java?

I want to add the values of integer column "priority" obtained from the MySQL db by iterating resultset using while loop. My piece of code is as below:

    int TotalWestPriority = 0;
    int WestPty = 0;

    float lat = 0;
    float lon = 0;

    float Wb_SWLat = 0; // Currently holds some value from other process
    float Wb_NELat = 0; // Currently holds some value from other process
    float Wb_SWLon = 0; // Currently holds some value from other process
    float Wb_NELon = 0; // Currently holds some value from other process


//SQL Query:
    String qryVcl = "select priority, latitude, longitude from tbl_vcl";

    ResultSet Vp=stmt.executeQuery(qryVcl);

    while(Vp.next()){
        lat = Vp.getFloat("latitude");
        lon = Vp.getFloat("longitude");
        System.out.println("Total Lat received:"+lat);

        if(lat >=Wb_SWLat && lat <=Wb_NELat && lon>=Wb_SWLon && lon<=Wb_NELon){
            WestPty = Vp.getInt("priority");
            System.out.println("West Priority:"+WestPty);
        }
        }

Here, I'am able to print the result:-

West Priority:3

West Priority:2

I want to add those values and store in an integer.

how to add all the "westpty" from the iteration to "TotalWestPriority" ?

Upvotes: 1

Views: 528

Answers (1)

Mureinik
Mureinik

Reputation: 311113

Just accumulate them to another variable:

long total = 0L;
while (vp.next()) {
    lat = vp.getFloat("latitude");
    lon = vp.getFloat("longitude");

    if (lat >= Wb_SWLat && lat <= Wb_NELat && 
        lon >= Wb_SWLon && lon <= Wb_NELon) {

        westPty = Vp.getInt("priority");
        System.out.println("West Priority:"+WestPty);

        total += westPty;
    }
}

System.out.println("Total west priority: " + total);

Upvotes: 3

Related Questions