【问题标题】:Count deleted records, returns 0统计删除的记录,返回 0
【发布时间】:2016-03-21 10:25:04
【问题描述】:

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

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

删除执行得很好。然后我想查看上次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 条记录被删除。

【问题讨论】:

    标签: sqlite jdbc prepared-statement


    【解决方案1】:

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

    final int deletedRowCount = stm.executeUpdate();
    

    【讨论】:

      【解决方案2】:

      documentation 说:

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

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

      【讨论】:

        猜你喜欢
        • 2012-03-18
        • 2011-07-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-16
        相关资源
        最近更新 更多