多语言展示
当前在线:1066今日阅读:86今日分享:14

jsp页面对数据库的增删改(二)

接着之前实现类的继续讲解
工具/原料

eclipse

方法/步骤
1

//连接数据库,将数据库中的数据,添加到集合public List listEmp() {  Connection con=null;  String sql=null;  Statement stmt=null;  ResultSet rs=null;

2

//声明集合(<>泛型)  List emps=new ArrayList();  try {   con= DBUtil.getConnection();   sql='select*from t_emp';   stmt=con.createStatement();//获取结果集   rs=stmt.executeQuery(sql);   while(rs.next()){

3

//遍历结果集,复制给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; }

4

public Emp findById(int id) {  //连接数据库  Connection con=null;  String sql=null;  Statement stmt=null;  ResultSet rs=null;

5

//实例化对象,赋值并返回  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; }

6

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);  } }

推荐信息