【问题标题】:How to find out if a Java ResultSet obtained is empty?如何判断获取的 Java ResultSet 是否为空?
【发布时间】:2011-02-25 16:45:49
【问题描述】:
Class.forName("org.sqlite.JDBC");
Connection conn =
    DriverManager.getConnection("jdbc:sqlite:userdata.db");
Statement stat = conn.createStatement();

ResultSet rs = stat.executeQuery("SELECT * from table WHERE is_query_processed = 0;");

int rowcount = rs.getRow(); 
System.out.println("Row count = "+rowcount); // output 1

rs.first(); // This statement generates an exception

为什么会这样?

【问题讨论】:

  • 我刚刚注意到您说调用first() 时引发了异常。抛出哪个异常?可能是因为你已经使用了getRow()而抛出一个,或者它可能是因为你的驱动程序不支持这种方法而抛出一个,在这种情况下,Colin 的解决方案更有可能为你工作。
  • @jasonmp:你说得对,我的驱动程序不支持调用 first()。我使用了 Collin 的解决方案,它对我有用。

标签: java database jdbc resultset


【解决方案1】:

我通常使用的模式如下:

boolean empty = true;
while( rs.next() ) {
    // ResultSet processing here
    empty = false;
}

if( empty ) {
    // Empty result set
}

【讨论】:

  • 这会将光标向右移动?所以为了进一步处理,第一条记录可能会丢失。
  • 如果您在此代码之后处理记录,您将错过第一条记录。但是,我通常在同一个 while 循环中处理记录。 (“//ResultSet processing here comment”在哪里。)这按预期工作并包括所有行。缺点是您不能只将支票粘贴到方法中。
【解决方案2】:

这是一个简单的方法:

public static boolean isResultSetEmpty(ResultSet resultSet) {
    return !resultSet.first();
}

注意事项

这会将光标移动到开头。但如果你只是想测试它是否为空,你可能还没有对它做任何事情。

或者

在进行任何处理之前立即使用first() 方法。 ResultSet rs = stat.executeQuery("SELECT * from table WHERE is_query_processed = 0;");

if(rs.first()) {
    // there's stuff to do
} else {
    // rs was empty
}

参考文献

ResultSet (Java Platform SE 6)

【讨论】:

    【解决方案3】:

    你也可以这样做:

    rs.last();
    int numberOfRows = rs.getRow();
    if(numberOfRows) {
        rs.beforeFirst();
        while(rs.next()) {
            ...
        }
    }
    

    【讨论】:

      【解决方案4】:
       while (results.next())
      

      用于遍历结果集。因此 results.next() 如果为空,将返回 false。

      【讨论】:

        【解决方案5】:

        为什么执行不进入 while 循环?

        如果您的 ResultSet 为空,则 rs.next() 方法将返回 false,并且不会输入 while 循环的主体,无论 rs.getRow() 返回的行号(不计数)如何。 Colins 示例有效。

        【讨论】:

        【解决方案6】:

        来回移动光标以确定行数不是正常的 JDBC 做法。正常的 JDBC 做法是将ResultSet 映射到一个值对象的List,每个值对象代表一个表行实体,然后只需使用List 方法来确定是否有任何行。

        例如:

        List<User> users = userDAO.list();
        
        if (users.isEmpty()) {
            // It is empty!
        if (users.size() == 1) {
            // It has only one row!
        } else {
            // It has more than one row!
        }
        

        list() 方法如下所示:

        public List<User> list() throws SQLException {
            Connection connection = null;
            Statement statement = null;
            ResultSet resultSet = null;
            List<User> users = new ArrayList<User>();
        
            try {
                connection = database.getConnection();
                statement = connection.createStatement();
                resultSet = statement.executeQuery(SQL_LIST);
                while (resultSet.next()) {
                    User user = new User();
                    user.setId(resultSet.getLong("id"));
                    user.setName(resultSet.getString("name"));
                    // ...
                    users.add(user);
                }
            } finally {
                if (resultSet != null) try { resultSet.close(); } catch (SQLException logOrIgnore) {}
                if (statement != null) try { statement.close(); } catch (SQLException logOrIgnore) {}
                if (connection != null) try { connection.close(); } catch (SQLException logOrIgnore) {}
            }
        
            return users;
        }
        

        有关其他 JDBC 示例,另请参阅 this answer

        【讨论】:

        • list 方法来自哪个类?它不在结果集上
        【解决方案7】:

        CLOSE_CURSORS_AT_COMMIT

        public static final int CLOSE_CURSORS_AT_COMMIT

        The constant indicating that ResultSet objects should be closed when the method Connection.commit is called. 
        

        【讨论】:

          【解决方案8】:

          试试这个:

          ResultSet MyResult = null;
          MyResult = Conexion.createStatement().executeQuery("Your Query  Here!!!");
          MyResult.last();
          int NumResut = MyResult.getRow();MyResult.beforeFirst();
          //Follow with your other operations....
          

          这样你就可以正常工作了。

          【讨论】:

            【解决方案9】:

            这会在不跳过第一条记录时检查它是否为空

            if (rs.first()) {
                do {
                    // ResultSet is not empty, Iterate over it
                } while (rs.next());
            } else {
                // ResultSet is empty
            }
            

            【讨论】:

              【解决方案10】:

              也许你可以将你的结果集对象转换为字符串对象并检查它是否为空。

              `if(resultset.toString().isEmpty()){
                   // containg null result
               }
               else{
                   //This conains the result you want
               }`
              

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2019-03-20
                • 2018-08-27
                • 1970-01-01
                • 1970-01-01
                • 2015-05-03
                相关资源
                最近更新 更多