首页 > 代码库 > RowMapper处理查询结果集

RowMapper处理查询结果集

查询返回单个结果(一个值或一个类),以下例子是返回password,返回一个类与该方法类似,使用内部匿名类方式

public boolean checkUser(User user)
{
String name = user.getUsername();
String pass = user.getPassword();
String sql="SELECT PASSWORD FROM USERS WHERE username=‘"+name+"‘";
Object obj=jdbcTemplate.queryForObject(sql, new RowMapper(){
public Object mapRow(java.sql.ResultSet res, int index)
throws SQLException {
// TODO Auto-generated method stub
String password=res.getString("password");
//System.out.println(password);
return password;
}

});
if(pass.equals(obj))
return true;
return false;
}

使用RowMapper查询多笔数据,使用继承接口方式

class UserRowMapper implements RowMapper { 
         public Object mapRow(ResultSet rs,int index) throws SQLException 
         { 
             User u = new User(); 
             u.setId(rs.getString(”ID”)); 
             u.setName(rs.getString(”Name”)); 
             u.setPassword(rs.getString(”Password”)); 
             return u; 
         } 
     } 
public List select(String where) 
    { 
        List list;        
        String sql = "select * from admin "+where;        
        list = jdbcTemplate.query(sql,new RowMapperResultReader(new UserRowMapper())); 
        return list; 
    }