【问题标题】:how to add values from a MySQL result-set while loop in java?java - 如何在Java中从MySQL结果集中的while循环中添加值?
【发布时间】:2017-05-03 17:35:34
【问题描述】:

我想通过使用 while 循环迭代结果集来添加从 MySQL 数据库获得的整数列“优先级”的值。我的一段代码如下:

    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”?

【问题讨论】:

  • 嗨,我只想添加从结果集迭代的 while 循环中出来的值并存储在一个整数中。任何一段代码都非常感谢,并在此先感谢。
  • 你的意思是你想总结每次迭代中检索到的所有值,比如3+2=5?
  • @PavneetSingh 是的,你是对的
  • 那就太简单了WestPty = WestPty +Vp.getInt("priority");
  • @PavneetSingh 我会试试的。谢谢

标签: java mysql jdbc resultset addition


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2014-04-09
    • 2013-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-28
    相关资源
    最近更新 更多