Get Number of Rows returned by ResultSet in Java

前端 未结 14 1245
挽巷
挽巷 2020-11-29 20:35

I have used a ResultSet that returns certain number of rows. My code is something like this:

ResultSet res = getData();
if(!res.next())
{
    Sy         


        
14条回答
  •  旧巷少年郎
    2020-11-29 20:51

    A simple getRowCount method can look like this :

    private int getRowCount(ResultSet resultSet) {
        if (resultSet == null) {
            return 0;
        }
    
        try {
            resultSet.last();
            return resultSet.getRow();
        } catch (SQLException exp) {
            exp.printStackTrace();
        } finally {
            try {
                resultSet.beforeFirst();
            } catch (SQLException exp) {
                exp.printStackTrace();
            }
        }
    
        return 0;
    }
    

    Just to be aware that this method will need a scroll sensitive resultSet, so while creating the connection you have to specify the scroll option. Default is FORWARD and using this method will throw you exception.

提交回复
热议问题