计算已删除的记录,返回0

时间:2016-03-21 10:25:04

标签: sqlite jdbc prepared-statement

我通过调用执行删除功能的方法DELETE从我的servlet在我的表中执行action.deleteBox(box); deleteBox方法

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

删除执行正常。然后我想检查从上一次删除中删除了多少条记录:所以我称这种方法为:

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记录被删除。

2 个答案:

答案 0 :(得分:2)

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

final int deletedRowCount = stm.executeUpdate();

答案 1 :(得分:1)

documentation说:

  

此函数返回由数据库连接上最近完成的INSERT,UPDATE或DELETE语句修改,插入或删除的行数

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