如何使用 count(*) 检查 table 是否为空

How to check table is empty with count(*)

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

       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;
   }

但是发生了一些错误,我收到一条错误消息 查询returns个结果

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 管理器看到 table,它是空的!

您正在执行 SELECT,因此您需要使用 executeQuery,而不是 executeUpdateexecuteUpdate 用于 UPDATEDELETEINSERT 等语句,executeQuery 用于执行 return 结果集(如 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,那么您 总是 有一行(带计数)。