Как получить все цены из определенного столбца добавить их и распечатать их - PullRequest
0 голосов
/ 09 октября 2018

У меня есть имя столбца (продажная цена) в базе данных, которая содержит все цены продукта, теперь я хочу добавить все отпускные цены и отобразить общую продажную цену.

, например:Столбец цены продажи содержит

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 голосов
/ 09 октября 2018
    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, полученного из набора результатов.Вы хотите что-то вроде:

 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; //<-- Create your total value outside of the while statement.
            while(rs.next()) {
                String total = rs.getString("sellingprice");
                totalValue += Integer.parseInt(total);//<-- Add the selling price from the current row to the total.
                System.out.println(totalValue); //<--This will print the latest total for each row in your result set
            }
            System.out.println(totalValue); //<-- This will print only the final total
        }catch(Exception e) {
            System.out.println(e.getMessage());
        }
    }      
0 голосов
/ 10 октября 2018

Попробуйте это решение, используя функцию 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());
 }
0 голосов
/ 09 октября 2018

Вы можете просто использовать 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 перед циклом и увеличивать ее внутри цикла.

выводить итоговое значение после циклазакончил.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...