需求
从stu表中读取数据,统计各个年龄段的人数,并输出到stu_res表中。
CREATE TABLE `stu` (
`id` int(11) NOT NULL DEFAULT '0',
`student_id` int(11) DEFAULT NULL,
`name` varchar(45) DEFAULT NULL,
`age` int(1) DEFAULT NULL,
`sex` varchar(1) DEFAULT NULL,
`birthday` varchar(45) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
数据:
INSERT INTO `stu` VALUES ('1', '1', 'zs', '12', '1', '2019-07-17');
INSERT INTO `stu` VALUES ('2', '2', 'goudan', '13', '1', '2019-07-17');
INSERT INTO `stu` VALUES ('3', '3', 'gg', '12', '2', '2019-07-17');
INSERT INTO `stu` VALUES ('4', '4', 'hh', '12', '2', '2019-07-17');
INSERT INTO `stu` VALUES ('5', '5', 'mm', '13', '1', '2019-07-17');
INSERT INTO `stu` VALUES ('6', '6', 'tt', '12', '1', '2019-07-17');
结果表:
CREATE TABLE `stu_res` (
`age` int(11) NOT NULL DEFAULT '0',
`cnt` int(11) DEFAULT 0
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
结果数据:
12 4
13 2
student类
因为结果只需要统计年龄,所以其他字段不在写。
public class Student {
private int id;
private int age;
public Student(int id, int age) {
this.id = id;
this.age = age;
}
public Student() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return this.id+" "+this.age;
}
}
Utils(用于c3p0连接数据库)
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import java.sql.SQLException;
import java.util.List;
public class Utils {
private static ComboPooledDataSource dataSource;
static{
dataSource = new ComboPooledDataSource();
}
public static QueryRunner getQuer