如何在java中循环时从MySQL结果集中添加值?

时间:2016-12-18 14:48:37

标签: java mysql jdbc resultset addition

我想添加整数列的值" priority"通过使用while循环迭代结果集从MySQL db获得。我的代码如下:

    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);
        }
        }

在这里,我能够打印出结果: -

West Priority:3

West Priority:2

我想添加这些值并存储在整数中。

如何添加所有&#34; westpty&#34;从迭代到&#34; TotalWestPriority&#34; ?

1 个答案:

答案 0 :(得分:3)

只需将它们累积到另一个变量:

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);