计数删除的记录,returns 0

Count deleted records, returns 0

我通过调用方法 action.deleteBox(box); 从我的 servlet 在我的 table 中执行一个 DELETE,该方法执行删除函数

删除框方法

Connection c = null;
PreparedStatement stm = null;
sq = "DELETE FROM BOXES WHERE ...";

try {       
    Class.forName(typeDB);
    c = DriverManager.getConnection(path);    
    stm = c.prepareStatement(sq);
    //...
    stm.executeUpdate();

} catch (SQLException e) {             
    System.out.println(e.getMessage());
} finally {
        System.out.println("my stm is closed : " + stm.isClosed());
        if (stm != null)
                    stm.close();
        if (c != null)
                    c.close();
}

删除执行正常。然后我想查看之前delete删除了多少条记录: 所以我调用这个方法:

public int countDeletesRecords() 
        throws SQLException, ClassNotFoundException {

    Connection c = null;
    PreparedStatement stm = null;
    sq = "SELECT changes() as \"deletedRows\" ";
    int deletedRows=-1;

    try {       
        Class.forName(typeDB);
        c = DriverManager.getConnection(path);    
        stm = c.prepareStatement(sq);       
        ResultSet rs = stm.executeQuery();

        if (rs.next()) {
            deletedRows = rs.getInt("deletedRows");
        }

    } catch (SQLException e) {             
        System.out.println(e.getMessage());
    } finally {
        System.out.println("my stm is closed : " + stm.isClosed());
        if (stm != null)
            stm.close();
        if (c != null)
            c.close();
    } 

    return deletedRows; //I get 0..
}

我得到 0 条记录,而 1 条记录被删除。

虽然这不能直接回答问题,但另一种更简单的方法是捕获 executeUpdate() 的 return 值,即 return 受影响的人数(在本例中, 删除) 行:

final int deletedRowCount = stm.executeUpdate();

documentation 说:

This function returns the number of rows modified, inserted or deleted by the most recently completed INSERT, UPDATE or DELETE statement on the database connection

您正在创建一个新的数据库连接,其中从未执行过任何 DELETE 语句。