eclipse
//连接数据库,将数据库中的数据,添加到集合public List
//声明集合(<>泛型) List
//遍历结果集,复制给emp对象,然后将emp对象添加到集合 Emp emp=new Emp(); emp.setId(rs.getInt('id')); emp.setName(rs.getString('name')); emp.setAge(rs.getInt('age')); emp.setSal(rs.getDouble('sal')); emps.add(emp); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ DBUtil.closeConnection(con); } return emps; }
public Emp findById(int id) { //连接数据库 Connection con=null; String sql=null; Statement stmt=null; ResultSet rs=null;
//实例化对象,赋值并返回 Emp emp=new Emp(); try { con=DBUtil.getConnection(); sql='select*from t_emp where id='+id; stmt=con.createStatement(); //根据id得到员工信息 rs=stmt.executeQuery(sql); //给员工赋值 while(rs.next()){ emp.setId(rs.getInt('id')); emp.setName(rs.getString('name')); emp.setAge(rs.getInt('age')); emp.setSal(rs.getDouble('sal')); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ DBUtil.closeConnection(con); } return emp; }
public void delete(int id) { Connection con=null; Statement stmt=null; String sql=null; try { con=DBUtil.getConnection(); stmt=con.createStatement(); sql='delete from t_emp where id='+id; stmt.executeUpdate(sql); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ DBUtil.closeConnection(con); } }