如何用count(*)检查表是空的

时间:2015-06-19 10:06:56

标签: sqlite jdbc prepared-statement

我正在尝试检查表是否为空。我编码这个方法:

       public boolean checkIfNULL()
           throws SQLException, ClassNotFoundException {

        boolean flag=false;
        System.out.println("Checking if table is empty...");
        String sq = "select count(*) from TABLE1";        
        try {       
            Class.forName(typeDB);
            c = DriverManager.getConnection(path);            
            stm = c.prepareStatement(sq);
            PreparedStatement stm = c.prepareStatement(sq);

            int rowsAffected = stm.executeUpdate();

            if(rowsAffected == 0)
                flag=true;

        } catch (SQLException e) {
        System.out.println(e.getMessage());
    } finally {
        if (stm != null) {
            stm.close();
        }
            if (c != null) {
                    c.close();
        }
        }

        return flag;
   }

但是错误是hapenning,我收到一条错误消息 查询返回结果

Exceptionn: java.sql.SQLException: [SQLITE_ERROR] SQL error or missing database (Connection is closed)

我如何检查check的返回值?

更新1: 我没有尝试上面的查询,而是尝试SELECT EXISTS(SELECT 1 FROM TABLE1) 但同样的事情正在发生..

更新2: 我用过这个:

    ResultSet rs = stm.executeQuery();

    if(!rs.next())
        flag=true;                  
    else
        System.err.println("ERROR - The table has records...");

并打印ERROR - "The table has records..."。这怎么可能?我通过SQLite管理器看到了表,它是空的!

1 个答案:

答案 0 :(得分:1)

您正在执行SELECT,因此您需要使用executeQuery,而不是executeUpdateexecuteUpdate适用于UPDATEDELETEINSERT等语句,executeQuery用于执行返回结果集的语句(如SELECT)。

您需要执行select语句,然后执行:

try (ResultSet rs = stm.executeQuery()) {
    rs.next(); // You always have a row, with the count
    int count = rs.getInt(1);
    flag = count == 0;
}

您的更新中的代码无效,因为如果您执行SELECT count(*) FROM table,那么始终会有一行(带有计数)。