我想做的是使用queryForObject从studentstable中选择用户名、密码和角色。
在我的 JdbcTemplate 语法中是
public static Object queryForObject(String sql,RowMAPPER mapper,Object ...args)
问题出在我的 JdbcStudentDAO 中
public class JdbcStudentDAO implements StudentDAO{
public String getLogin(StudentTO sto) {
String sql="select username,password,role from studentstable";
System.out.println(sql);
这里我不知道下面出了什么问题
Object obj=JdbcTemplate.queryForObject(sql,new StudentRowMapper(),sto.getUsername(),sto.getPassword(),sto.getRole());
StudentTO sto1=(StudentTO)obj;
System.out.println(sto1);
return sto1.toString();
}
}
这是我的 RowMapper,我可以在其中获取数据库的所有行,如下所示
public class StudentRowMapper implements RowMapper{
public Object mapRow(ResultSet rs) throws SQLException {
StudentTO sto=new StudentTO();
sto.setSid(rs.getInt(1));
sto.setName(rs.getString(2));
sto.setUsername(rs.getString(3));
sto.setPassword(rs.getString(4));
sto.setEmail(rs.getString(5));
sto.setPhone(rs.getLong(6));
sto.setRole(rs.getString(7));
return sto;
}
}
这是StudentDAO中的抽象方法
public interface StudentDAO {
public String getLogin(StudentTO sto);
}
最佳答案
这是您的查询
select username,password,role from studentstable
您只有 3 列,并且它们不按照您提取定义的顺序...
sto.setSid(rs.getInt(1)); sto.setName(rs.getString(2)); sto.setUsername(rs.getString(3)); // This is actually index 1 sto.setPassword(rs.getString(4)); // This is actually index 2 sto.setEmail(rs.getString(5)); sto.setPhone(rs.getLong(6)); sto.setRole(rs.getString(7)); // This is actually index 3
因此,您需要这个
sto.setUsername(rs.getString(1));
sto.setPassword(rs.getString(2));
sto.setRole(rs.getString(3));
其他属性均为默认值
关于java - 如何使用 queryForObject 和 rowMapper 从表中获取一行或多行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45065187/