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;
}
}
This is my another class:
public class Demo {
public static void main(String[] args){
GetCurrentDateTime obj = new GetCurrentDateTime();
System.out.println(obj.data());
}
}
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;
}