Search

Thứ Ba, 21 tháng 1, 2014

Sum of Column in a Database Table (Tổng cột trong một Bảng cơ sở dữ liệu trong java)

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class Main {
  public static void main(String[] argv) throws Exception {
    int sum = 0;
    Class.forName("com.mysql.jdbc.Driver");
    Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbctutorial",
        "root", "root");
    Statement st = con.createStatement();
    ResultSet res = st.executeQuery("SELECT SUM(col) FROM mytable");
    while (res.next()) {
      int c = res.getInt(1);
      sum = sum + c;
    }
    System.out.println("Sum of column = " + sum);
  }
}

0 nhận xét:

Đăng nhận xét

 
Le Van Chat