JDBC操作数据库

使用preparestatement执行查找语句
UserDao的实现类UserDaoImpl中,使用preparestatement执行查询语句的操作:
1.findById方法:
public User finById(int id) {
		User user=null;
		try {
			conn=this.getConnection();
			String sql="select * from users where id="+id;
			pstmt=conn.prepareStatement(sql);
			rs=pstmt.executeQuery();
			while(rs.next()){
				user=new User();
				user.setId(rs.getInt("id"));
				user.setName(rs.getString("name"));
				user.setPassword(rs.getString("password"));
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return user;
		
	}
	
2.findAll方法:
	public List findAll() {
		List list=new ArrayList();
		try {
			conn=this.getConnection();
			String sql="select * from users ";
			pstmt=conn.prepareStatement(sql);
			rs=pstmt.executeQuery();
			while(rs.next()){
				User user=new User();
				user.setId(rs.getInt("id"));
				user.setName(rs.getString("name"));
				user.setPassword(rs.getString("password"));
				list.add(user);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return list;

		
	}
3.登陆login方法:ligin方法就是通过上面所说的fnidById的方法实现的。
public User login(String name, String password) {
		User user=null;
		try {
			conn=this.getConnection();
			String sql="select * from users where name=? and password=?";
			pstmt=conn.prepareStatement(sql);
			pstmt.setString(1, name);
			pstmt.setString(2, password);
			rs=pstmt.executeQuery();
			while(rs.next()){
				user=new User();
				user.setId(rs.getInt("id"));
				user.setName(rs.getString("name"));
				user.setPassword(rs.getString("password"));
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return user;
	}
4.分页:关键代码是sql语句:
public List findAll(int page) {
        List list=new ArrayList();
        int begin=(page-1)*5;
        try {
            conn=this.getConnection();
            String sql="SELECT TOP 5 *  FROM users WHERE " +
                    "(ID NOT IN  (SELECT TOP "+begin+" id   FROM users  ORDER BY id desc))" +
                    "ORDER BY ID desc ";
            pstmt=conn.prepareStatement(sql);
            rs=pstmt.executeQuery();
            while(rs.next()){
                User    user=new User();
                user.setId(rs.getInt("id"));
                user.setName(rs.getString("name"));
                user.setPassword(rs.getString("password"));
                list.add(user);
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        return list;
    }









评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值