DAO:Data Access Object

  DAO    数据层

  Service   逻辑业务层

  View     视图层

  entity     实体层

实现增、删、改、查的数据层

 public class EmpDAO {

     public Employee findEmpById(int id) {

         Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
Employee emp = null; conn = DBTool.getInstance().getConnection();
String sql = "SELECT * FROM Employee WHERE empId = ?";
try {
ps = conn.prepareStatement(sql);
ps.setInt(1, id);
rs = ps.executeQuery();
while(rs.next()){
emp = new Employee();
emp.setEmpNo(rs.getInt("empId"));
emp.seteName(rs.getString("empName"));
emp.setSalary(rs.getDouble("salary"));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
DBTool.closeAll(conn, ps, rs);
}
return emp;
}
public int addEmp(Employee emp){
int row = 0;
Connection conn = null;
PreparedStatement ps = null;
conn = DBTool.getInstance().getConnection();
String sql = "INSERT INTO Employee (empName,salary) values (?,?)";
try {
ps = conn.prepareStatement(sql);
ps.setString(1, emp.geteName());
ps.setDouble(2, emp.getSalary());
row = ps.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
DBTool.closeAll(conn, ps, null);
}
return row;
}
public int updateEmp(Employee emp){
int row = 0;
Connection conn = null;
PreparedStatement ps = null;
conn = DBTool.getInstance().getConnection();
String sql = "UPDATE Employee SET empName = ?,Salary = ? WHERE empId = ?";
try {
ps = conn.prepareStatement(sql);
ps.setString(1, emp.geteName());
ps.setDouble(2, emp.getSalary());
ps.setInt(3, emp.getEmpNo());
row = ps.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
DBTool.closeAll(conn, ps, null);
}
return row;
}
public int deleteEmp(int id){
int row = 0;
Connection conn = null;
PreparedStatement ps = null;
conn = DBTool.getInstance().getConnection();
String sql = "delete from employee where empId = ?";
try {
ps = conn.prepareStatement(sql);
ps.setInt(1, id);
row = ps.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
DBTool.closeAll(conn, ps, null);
}
return row;
}
}
05-07 15:45