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

Sqlite 如何使用count(*)检查表是否为空,sqlite,jdbc,prepared-statement,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 TAB

我正在检查桌子是否空着。我将此方法编码为:

       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;
   }
但是出了点问题,我收到了一条错误信息 查询返回结果

Exceptionn: java.sql.SQLException: [SQLITE_ERROR] SQL error or missing database (Connection is closed)
如何检查支票的返回值

更新1: 我尝试了从表1中选择existsselect1,而不是上面的查询 但同样的情况正在发生

更新2: 我用了这个:

    ResultSet rs = stm.executeQuery();

    if(!rs.next())
        flag=true;                  
    else
        System.err.println("ERROR - The table has records...");
然后打印错误-表中有记录。。。。这怎么可能?我通过SQLite管理器看到表,它是空的

您正在执行SELECT,因此需要使用executeQuery,而不是executeUpdate。executeUpdate用于UPDATE、DELETE和INSERT等语句,executeQuery用于执行返回SELECT等结果集的语句

您需要执行select语句,并执行以下操作:

try ResultSet rs=stm.executeQuery{ rs.next;//您总是有一行,带有计数 int count=rs.getInt1; 标志=计数==0; }
更新中的代码不起作用,因为如果从表中选择count*,则始终有一行包含该计数。

我建议不要这样做。通常,我会推荐某种形式的EXISTS,但我认为SQLite不支持这种方式——但我仍然建议,比如说,运行一个限制为1的基本查询。如果您只关心不存在行且至少存在一行的情况,则不需要强制引擎计算每一行。一旦你看到任何一行,你就会知道答案。如果你发布了一个异常,那么请包括完整的stacktrace,它提供的信息可能有助于跟踪原因。