如何从特定列获取所有价格,将其添加并打印

时间:2018-10-09 15:51:42

标签: java mysql jdbc

我在一个包含产品所有价格的数据库中有一个列名(销售价格),现在我想要添加所有销售价格并显示总销售价格。

例如:售价列包含

Selling price
-------------
580
580
20

我想将所有售价相加,并在总数为1180的情况下显示总数。

try {
     Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost/customerinfo", "root", "");
     Statement st = con.createStatement();
     ResultSet rs;
     String mysqlQuery = "SELECT `sellingprice` FROM cust_info";
     rs =st.executeQuery(mysqlQuery);
     while(rs.next()) {
        String total = rs.getString("sellingprice"); // getting all the selling prices
          //converting to integer
          int totalValue = Integer.parseInt(total);
          // what logic should goes here....
          System.out.println(totalValue);    
     }
 }catch(Exception e) {
     System.out.println(e.getMessage());
 }

3 个答案:

答案 0 :(得分:2)

您可以像上面的注释一样在查询中使用SUM,也可以执行以下操作:

try {
 Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost/customerinfo", "root", "");
 Statement st = con.createStatement();
 ResultSet rs;
 String mysqlQuery = "SELECT `sellingprice` FROM cust_info";
 rs =st.executeQuery(mysqlQuery);

 int totalValue = 0;
 while(rs.next()) {    
     totalValue += rs.getInt("sellingprice");
 }
 System.out.println"The total Value is: " + totalValue; 
}catch(Exception e) {
 System.out.println(e.getMessage());
}

我更改了以下内容

rs.getInt而不是rs.getString,您还可以根据期望的数据使用getDouble

在循环之前声明并初始化int变量,并在循环内对其进行递增。

在循环结束后打印总数。

答案 1 :(得分:1)

Volley

您无法在 try { Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost/customerinfo", "root", ""); Statement st = con.createStatement(); ResultSet rs; String mysqlQuery = "SELECT `sellingprice` FROM cust_info"; rs =st.executeQuery(mysqlQuery); while(rs.next()) { String total = rs.getString("sellingprice"); // getting all the selling prices //converting to integer int totalValue = Integer.parseInt(total);//<----- YOUR PROBLEM // what logic should goes here.... System.out.println(totalValue); } }catch(Exception e) { System.out.println(e.getMessage()); } 语句中创建totalValue。每次代码循环遍历while语句时,您都将将总值重置为从结果集中获得的最新值while。您想要类似的东西:

total

答案 2 :(得分:0)

使用SUM函数尝试此解决方案:

try {
 Connection con = (Connection) 
 DriverManager.getConnection("jdbc:mysql://localhost/customerinfo", "root", "");
 Statement st = con.createStatement();
 ResultSet rs;
 String mysqlQuery = "SELECT SUM(`sellingprice`) FROM cust_info";
 rs =st.executeQuery(mysqlQuery);
 int totalValue  = 0;
 if(rs.next()) {
      String total = rs.getString("sellingprice");
      if(total != null){
          totalValue  = Integer.parseInt(total);    
      }
      System.out.println(totalValue);
 }
 }catch(Exception e) {
 System.out.println(e.getMessage());
 }