从MySQL数据库获取Java中的Sum(total) [英] Get Sum(total) in Java from MySQL database

查看:905
本文介绍了从MySQL数据库获取Java中的Sum(total)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据库 - pro 。表名为 订单 。该表有一个字段 - 总计 。总数值为 (100,200,300,400,500) 。现在我需要添加上面数据库中的所有值。我怎么能用Java做到这一点?如何用Java编写查询?请帮我。这是我的代码部分:

I have one database - pro. The table name is orders. The table have one field - total. The total have values - (100,200,300,400,500). Now I need to add all values from above database. How can I do this in Java? How can I write the query in Java? Please help me. This is my code part:

    public class GetCurrentDateTime {
     private Object sum;
    public int data(){  

try{
    Class.forName("com.mysql.jdbc.Driver");
    Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/pro","root","");

    PreparedStatement statement =  con.prepareStatement("select sum(total) from orders where status='Q' AND WEEK(date) = WEEK(CURDATE()) AND YEAR(date) = YEAR(CURDATE())");
     ResultSet result = statement.executeQuery();
     println(result,getString(1));
    }

      catch(Exception exc){
      System.out.println(exc.getMessage());
      }
return 0;   
      }

    private void println(ResultSet result, Object string) {
// TODO Auto-generated method stub

     }
      private Object getString(int i) {
// TODO Auto-generated method stub
return sum;
    }
     }

这是我的另一个班级:

      public class Demo {
    public static void main(String[] args){
    GetCurrentDateTime obj = new GetCurrentDateTime();
    System.out.println(obj.data());

    }

   }

如果我有运行我的演示类意味着总数的总和显示在tomcat控制台窗口上。但是它仅显示为null 0。如何在Java中调用 sum(total)函数?请帮帮我。

If I have to run my demo class means the sum of total number is displayed on tomcat console window. But is it displayed null 0 only. How to call sum(total) function in Java? Please help me.

推荐答案

试试这个而不是你的数据方法

Try this instead your data method

public double data(){
  double value=0.0;
  try{
     Class.forName("com.mysql.jdbc.Driver");
     Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/pro","root","");

     PreparedStatement statement =  con.prepareStatement("select sum(total) from orders where status='Q' AND WEEK(date) = WEEK(CURDATE()) AND YEAR(date) = YEAR(CURDATE())");
     ResultSet result = statement.executeQuery();
     result.next();
     String sum = result.getString(1);
     System.out.println(sum);
     value = Double.parseDouble(sum);

    } catch(Exception exc){
        System.out.println(exc.getMessage());
    }
    return value;
}

这篇关于从MySQL数据库获取Java中的Sum(total)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆