Spring JDBC获取查询返回的值

时间:2012-08-21 15:01:41

标签: java sql spring jdbc spring-jdbc

您好我有一个查询,我从数据库中选择值,我想与选定的数据进行比较。我能够创建查询并传入参数,但我仍然在访问查询返回的值时遇到一些问题。有人可以告诉我,如果我在正确的轨道上,我想我写的最后两个错误。

    String sql = "SELECT userName, password FROM tblusers WHERE userName = ? AND password = ? ";



    Object[] parameters = new Object[] {login.getUserName(), login.getPassword()};

    String dbUserName = (String)getJdbcTemplate().queryForObject(
            sql, parameters, String.class);

    String dbPassword = (String)getJdbcTemplate().queryForObject(
            sql, parameters, String.class);

2 个答案:

答案 0 :(得分:4)

如果您的查询只返回一条记录,我建议您使用:

queryForMap(String sql, Object... args)

看看javadoc。

对于您的具体问题,这应该有效:

Map<String,Object> results = 
        getJdbcTemplate().queryForMap(
            "SELECT userName, password FROM tblusers WHERE userName = ? AND password = ?"
            , login.getUserName()
            , login.getPassword());

String dbUserName = (String)results.get("userName");
String dbPassword = (String)results.get("password");

答案 1 :(得分:2)

您的查询将返回两个字符串,如果这是您想要的,那么您应该将结果转换为对象,或者只是在一次查询用户名和密码。以下是如何使用行映射器同时获取用户名和密码。

    public class CustomRowMapper implements RowMapper {

        public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
            User user = new User();
            user.setPassword(rs.getString("password");
            user.setUserName(rs.getString("userName"); 
            return user;  
        }
    }


    String sql = "SELECT userName, password FROM tblusers WHERE userName = ? AND password =        ? ";

    Object[] parameters = new Object[] {login.getUserName(), login.getPassword()};

    User u = (User) getJdbcTemplate().queryForObject(sql, parameters, new CustomRowMapper());

否则......

String sql = "SELECT userName FROM tblusers WHERE userName = ? AND password = ? ";

String userName = getJdbcTemplate().queryForString(sql, parameters);

String passwordSql = String sql = "SELECT password FROM tblusers WHERE userName = ? AND password = ? ";

String password= getJdbcTemplate().queryForString(sql, parameters);