How to get row count using ResultSet in Java?

前端 未结 13 2063
[愿得一人]
[愿得一人] 2020-11-27 13:05

I\'m trying to create a simple method that receives a ResultSet as a parameter and returns an int that contains the row count of the ResultSet. Is this a valid way of doing

相关标签:
13条回答
  • 2020-11-27 13:34

    I just made a getter method.

    public int getNumberRows(){
        try{
           statement = connection.creatStatement();
           resultset = statement.executeQuery("your query here");
           if(resultset.last()){
              return resultset.getRow();
           } else {
               return 0; //just cus I like to always do some kinda else statement.
           }
        } catch (Exception e){
           System.out.println("Error getting row count");
           e.printStackTrace();
        }
        return 0;
    }
    
    0 讨论(0)
  • 2020-11-27 13:35

    Here's some code that avoids getting the count to instantiate an array, but uses an ArrayList instead and just before returning converts the ArrayList to the needed array type.

    Note that Supervisor class here implements ISupervisor interface, but in Java you can't cast from object[] (that ArrayList's plain toArray() method returns) to ISupervisor[] (as I think you are able to do in C#), so you have to iterate through all list items and populate the result array.

    /**
     * Get Supervisors for given program id
     * @param connection
     * @param programId
     * @return ISupervisor[]
     * @throws SQLException
     */
    public static ISupervisor[] getSupervisors(Connection connection, String programId)
      throws SQLException
    {
      ArrayList supervisors = new ArrayList();
    
      PreparedStatement statement = connection.prepareStatement(SQL.GET_SUPERVISORS);
      try {
        statement.setString(SQL.GET_SUPERVISORS_PARAM_PROGRAMID, programId);
        ResultSet resultSet = statement.executeQuery();  
    
        if (resultSet != null) {
          while (resultSet.next()) {
            Supervisor s = new Supervisor();
            s.setId(resultSet.getInt(SQL.GET_SUPERVISORS_RESULT_ID));
            s.setFirstName(resultSet.getString(SQL.GET_SUPERVISORS_RESULT_FIRSTNAME));
            s.setLastName(resultSet.getString(SQL.GET_SUPERVISORS_RESULT_LASTNAME));
            s.setAssignmentCount(resultSet.getInt(SQL.GET_SUPERVISORS_RESULT_ASSIGNMENT_COUNT));
            s.setAssignment2Count(resultSet.getInt(SQL.GET_SUPERVISORS_RESULT_ASSIGNMENT2_COUNT));
            supervisors.add(s);
          }
          resultSet.close();
        }
      } finally {
        statement.close();
      }
    
      int count = supervisors.size();
      ISupervisor[] result = new ISupervisor[count];
      for (int i=0; i<count; i++)
        result[i] = (ISupervisor)supervisors.get(i);
      return result;
    }
    
    0 讨论(0)
  • 2020-11-27 13:36
    Statement s = cd.createStatement();
    ResultSet r = s.executeQuery("SELECT COUNT(*) AS rowcount FROM FieldMaster");
    r.next();
    int count = r.getInt("rowcount");
    r.close();
    System.out.println("MyTable has " + count + " row(s).");
    

    Sometimes JDBC does not support following method gives Error like `TYPE_FORWARD_ONLY' use this solution

    Sqlite does not support in JDBC.

    resultSet.last();
    size = resultSet.getRow();
    resultSet.beforeFirst();
    

    So at that time use this solution.

    Thanks..

    0 讨论(0)
  • 2020-11-27 13:39

    Most drivers support forward only resultset - so method like last, beforeFirst etc are not supported.

    The first approach is suitable if you are also getting the data in the same loop - otherwise the resultSet has already been iterated and can not be used again.

    In most cases the requirement is to get the number of rows a query would return without fetching the rows. Iterating through the result set to find the row count is almost same as processing the data. It is better to do another count(*) query instead.

    0 讨论(0)
  • 2020-11-27 13:43

    Do a SELECT COUNT(*) FROM ... query instead.

    0 讨论(0)
  • 2020-11-27 13:45

    Your function will return the size of a ResultSet, but its cursor will be set after last record, so without rewinding it by calling beforeFirst(), first() or previous() you won't be able to read its rows, and rewinding methods won't work with forward only ResultSet (you'll get the same exception you're getting in your second code fragment).

    0 讨论(0)
提交回复
热议问题