簡體   English   中英

如何在Java中的while循環中從MySQL結果集中添加值?

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

我想通過使用while循環迭代結果集來添加從MySQL db獲得的整數列“ priority”的值。 我的代碼如下:

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

在這里,我可以打印結果:

西部優先:3

西部優先:2

我想將這些值相加並存儲為整數。

如何將迭代中的所有“ westpty”添加到“ TotalWestPriority”?

只需將它們累加到另一個變量中:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM