封装一个 员工类 使用preparedStatement 查询数据 (2) 使用 arrayList 集合

时间:2021-08-05 15:52:43
创建 员工=类生成 有参构造 get set 方法 toString 方法

package cn.hph; public class emp1 { //创建员工类的属性
   private  int id; private String ename; private int Job_id; private int mgr; private String Joindate; private Double salary; private Double bonus; private int dept_id; //生成get set 方法
    public int getId() { return id; } public void setId(int id) { this.id = id; } public String getEname() { return ename; } public void setEname(String ename) { this.ename = ename; } public int getJob_id() { return Job_id; } public void setJob_id(int job_id) { Job_id = job_id; } public int getMgr() { return mgr; } public void setMgr(int mgr) { this.mgr = mgr; } public String getJoindate() { return Joindate; } public void setJoindate(String joindate) { Joindate = joindate; } public Double getSalary() { return salary; } public void setSalary(Double salary) { this.salary = salary; } public Double getBonus() { return bonus; } public void setBonus(Double bonus) { this.bonus = bonus; } public int getDept_id() { return dept_id; } public void setDept_id(int dep_id) { this.dept_id = dep_id; } //生成有参构造
    public emp1(int id, String ename, int job_id, int mgr, String joindate, Double salary, Double bonus, int dept_id) { this.id = id; this.ename = ename; Job_id = job_id; this.mgr = mgr; Joindate = joindate; this.salary = salary; this.bonus = bonus; this.dept_id = dept_id; } //生成toString 方法
    public String toString() { return "id=" + id +
                ", ename='" + ename + '\'' +
                ", Job_id=" + Job_id +
                ", mgr=" + mgr +
                ", Joindate='" + Joindate + '\'' +
                ", salary=" + salary +
                ", bonus=" + bonus +
                ", dep_id=" + dept_id; } }
 

使用ArrayList集合查询表中的数据

package cn.hph; import jdbcUtil.JdbcUtil; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; public class ArrayListSelect { public static void main(String[] args){ //创建ArrayList 集合
        ArrayList<emp1> arr= new ArrayList<emp1>(); try { //调用Jdbc 工具类
            Connection conn = JdbcUtil.getConnection(); //获得 preparedStatement 方法
            PreparedStatement pre   = conn.prepareStatement("select * from emp"); //执行sql语句
            ResultSet rs = pre.executeQuery(); while(rs.next()) { //员工表的属性添加到集合中
                arr.add(new emp1(rs.getInt("id"), rs.getString("ename"), rs.getInt("job_id"), rs.getInt("mgr"), rs.getString("joindate"), rs.getDouble("salary"), rs.getDouble("bonus"), rs.getInt("dept_id"))); } //使用增强for循环遍历
            for(emp1 m:arr){ System.out.println(m.toString()); } // 关闭流
 JdbcUtil.close(pre,conn); } catch (SQLException e) { e.printStackTrace(); } } }