关于DAO层的学习

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

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值