定义一个方法,查询emp表的数据将其封装为对象,返回
定义emp;类编写对应字段。
定义方法 public List <Emp> find(){ }
实现方法 select * from emp;
java代码实例:
@Data @NoArgsConstructor @AllArgsConstructor public class Emp { private int id; private String ename; private int job_id; private int mgr; private Date joindate; private double salary; private double bounds; private int dept_id; }
public static void main(String[] args) { List<Emp> all = new jdbcdemo08().findAll(); System.out.println(all); System.out.println(all.size()); } public List<Emp> findAll(){ List<Emp> list = null; Connection connection = null; ResultSet resultSet = null; Statement statement = null; try { Class.forName("com.mysql.cj.jdbc.Driver"); connection = DriverManager.getConnection("jdbc:mysql:///a2", "root", "root"); String sql = "select * from emp"; statement = connection.createStatement(); resultSet = statement.executeQuery(sql); Emp emp = null; list = new ArrayList<>(); while (resultSet.next()){ int id = resultSet.getInt("id"); String ename = resultSet.getString("ename"); int job_id = resultSet.getInt("job_id"); int mgr = resultSet.getInt("mgr"); Date joindate = resultSet.getDate("joindate"); double salary = resultSet.getDouble("salary"); double bonus = resultSet.getDouble("bonus"); int dept_id = resultSet.getInt("dept_id"); emp = new Emp(); emp.setId(id); emp.setEname(ename); emp.setJob_id(job_id); emp.setMgr(mgr); emp.setJoindate(joindate); emp.setSalary(salary); emp.setBounds(bonus); emp.setDept_id(dept_id); list.add(emp); } } catch (ClassNotFoundException e) { e.printStackTrace(); }catch (SQLException e){ e.printStackTrace(); }finally { if (resultSet !=null){ try { resultSet.close(); } catch (SQLException e) { e.printStackTrace(); } } if (statement !=null){ try { statement.close(); } catch (SQLException e) { e.printStackTrace(); } } if (connection !=null){ try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } } } return list; }