简体   繁体   English

计算从mysql数据库检索的行数

[英]Count number of rows retrieved from mysql database

public int countBookings() throws SQLException{

    ResultSet rs=null;
    PMDBController db=new PMDBController();
    int rowCount=0;

    db.getConnection();

    String dbQuery="SELECT COUNT(User) AS UserCount FROM INSTRUCTORBOOKING WHERE USER ='"+instructorId+"'";

    rs=db.readRequest(dbQuery);

    try{
        if(rs.next()){
            instructorId=rs.getString("UserCount");
        }
    }catch(Exception e){
        e.printStackTrace();
    }

    rs.last();
    rowCount=rs.getRow();
    db.terminate();

    return rowCount;
}

Basically what this method is supposed to do is count the number of rows gotten from the database. 基本上,该方法应该做的是计算从数据库中获得的行数。 However, it always returns 1 no matter what is inside. 但是,无论内部是什么,它总是返回1。 Help! 救命!

It seems you have a problem in your query. 看来您的查询有问题。 Since you only select 1 user you will always get a count of 1. 由于您只选择1个用户,因此总计数为1。

"SELECT COUNT(User) AS UserCount FROM INSTRUCTORBOOKING WHERE USER ='"+instructorId+"'"

Try removing your WHERE clause? 尝试删除您的WHERE子句? Maybe that's not exactly what you want, but we can't see your data model from just one query. 也许这并不是您想要的,但是我们无法仅通过一个查询看到您的数据模型。

rowCount = rs.getInt("UserCount"); instead of instructorId = rs.getString("UserCount"); 而不是instructorId = rs.getString("UserCount"); would do the trick. 会成功的 Or in other words --- you read the number of rows but into variable instructorId. 换句话说,您读取了行数,但读取到了变量utororId中。

The number of rows will always be 1. It's the count ie the value of that row you need to look at as your query is designed to return the count of rows and not the actual rows. 行数始终为1。它是计数,即您需要查看的该行的值,因为查询被设计为返回行数而不是实际行数。

SELECT COUNT(User) AS UserCount FROM INSTRUCTORBOOKING WHERE USER ='"+instructorId+"'"

You have wrongly interpreted that the number of rows would be the count you are looking for. 您错误地认为行数就是您要查找的计数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM