其他分享
首页 > 其他分享> > ResultSet 赋值问题

ResultSet 赋值问题

作者:互联网

问题:

//操作数据库的公共类
public class BaseDao {
...

    /*编写查询公共类*/
    public static ResultSet execute(Connection con,PreparedStatement preparedStatement,ResultSet resultSet,String sql,Object[] params) throws SQLException {
   		preparedStatement = con.prepareStatement(sql);

        for (int i = 0; i < params.length; i++) {
            preparedStatement.setObject(i+1,params[i]);
        }
        resultSet = preparedStatement.executeQuery();
        return resultSet;
	}
    
...
}

public class UserDaoImpl implements UserDao{
    //根据用户名或角色查询用户总数
@Override
public int getUserCount(Connection connection, String userName, int userRole) throws SQLException {
    PreparedStatement pstm = null;
    ResultSet rs = null;
    int count = 0;

    if(connection != null){
        StringBuffer sql = new StringBuffer();
        sql.append("select count(1) as count from smbms_user u,smbms_role r where u.userRole = r.id ");

        //用来传参数
        List<Object> list = new ArrayList<>();

        if(!StringUtils.isNullOrEmpty(userName)){
            sql.append("and u.userName like ? ");
            list.add("%"+userName+"%");
        }
        if(userRole > 0){
            sql.append("and u.userRole=?");
            list.add(userRole);
        }

        //输出完整sql
        System.out.println("sql:" + sql.toString());

        rs = BaseDao.execute(connection,pstm,rs,sql.toString(),list.toArray());

        if(rs.next()){
            count = rs.getInt("count");
        }
        BaseDao.closeSourse(null,pstm,rs);
    }
        return count;
    }
}

​ 在BaseDao.execute(Connection con,PreparedStatement pstm,ResultSet rs,String sql,Object[] params)中参数rs在最后已经被赋值了,那调用这个方法的方法中的rs应该也赋好了值,为何在UserDaoImpl中还需要写

rs = BaseDao.execute(connection,pstm,rs,sql.toString(),list.toArray());,用返回值对rs进行赋值,而不是在调用BaseDao.execute已经赋好了。

如果不用返回值对rs进行赋值,那后面的rs.next()就会报错。

解答:

​ 待解答。。。

标签:count,execute,rs,ResultSet,BaseDao,问题,sql,pstm,赋值
来源: https://www.cnblogs.com/zlaoyao/p/16411980.html