DAO的模型
DAO(Date Access Object) 模型就是写一个类,把访问数据库的代码封装起来,DAO在数据库与业务逻辑(Service)之间。
如果我需要对service的需求修改,无需改变dao层的代码,只要在实现上改变即可,如果我有访问数据库的新需求,那我也只要在dao层的代码中增添即可。
service层代码
IStudentService接口
public interface IStudentService {
Student checkUser(String num,String password);
}
StudentServiceImpl(实现IStudentService接口)
public class StudentServiceImpl implements IStudentService {
private IStudentDao dao;
public StudentServiceImpl() {
dao = new StudentDaoImpl();
}
public Student checkUser(String num, String password) {
return dao.selectStudentLogin(num,password);
}
}
Dao层代码
IStudentDao接口
public interface IStudentDao {
Student selectStudentLogin(String num, String password);
}
StudentDaoImpl(实现IStudentDao接口)
public class StudentDaoImpl implements IStudentDao {
private Connection conn;
private Statement st;
private PreparedStatement ps;
private ResultSet rs;
public Student selectStudentLogin(String num, String password) {
Student student = null;
try {
conn = JdbcUtils.getConnection();
String sql = "select * from student where num=? and password=?";
ps = conn.prepareStatement(sql);
ps.setString(1, num);
ps.setString(2, password);
rs = ps.executeQuery();
if(rs.next()) {
student = new Student();
student.setId(rs.getInt("id"));
student.setNum(rs.getString("num"));
student.setName(rs.getString("name"));
student.setAge(rs.getInt("age"));
student.setPassword(rs.getString("password"));
student.setScore(rs.getDouble("score"));
}
} catch(SQLException e) {
e.printStackTrace();
} finally {
try {
JdbcUtils.close(conn, st, rs);
} catch (SQLException e) {
e.printStackTrace();
}
}
return student;
}
}