3:50 pm - Wednesday February 19, 7564

Statement GROUP BY Example program in java Jdbc mysql database

CANDID INDUSTRIAL TRAINING -- CHENNAI
Corporate Training for Experienced Candidate
Struts | Hibernate | Spring | Java / J2EE
SOAP | RestFull | Design Pattern | more...
Ph: +91 72000 69003
137b, 2nd st, shanthi nagar, Chrompet, Chennai -600044

Create Table and  Insert values:

mysql>Create table EMP (name varchar(12),id int(5),salary int(10));
INSERT INTO EMP(name,id,salary) VALUES("Arun",1,2500 );
INSERT INTO EMP(name,id) VALUES("Dinesh",3 );
INSERT INTO EMP(name,id,salary) VALUES("Karthik",3,5000 );
INSERT INTO EMP(name,id,salary) VALUES("Tamil",4,2500 );
Query OK, 0 rows affected (0.06 sec)

Input:

Java code:

package myjava1;

import java.sql.*;

public class Groupby {

	/**
	 * @param args
	 */

	// TODO Auto-generated method stub

	public static void main(String[] args) throws Exception {

		Class.forName("com.mysql.jdbc.Driver").newInstance();
		Connection conn = DriverManager.getConnection(
				"jdbc:mysql://localhost:3306/Arun", "root", "root");
		Statement st = conn.createStatement();

		st = conn.createStatement();
		ResultSet rs = st
				.executeQuery("  SELECT name,SUM(salary)from Emp GROUP BY name");

		while (rs.next()) {
			String name = rs.getString(1);
			String salary = rs.getString(2);
			System.out.println(name);
			System.out.println(salary);

		}

		rs.close();
		st.close();
		conn.close();

	}

}

Output:

Filed in: Z-A All Java Codes

Comments are closed.