尽管未收到错误,Java SQL更新语句仍未在表中更新

时间:2019-01-19 11:48:30

标签: java mysql sql jdbc

public void updateFields(BorrowedBook borrowedBook) throws SQLException {
    Integer copiesInBorrow = new Integer(0);
    Integer availableCopies = new Integer(0);
    PreparedStatement pstmt;
    try {
        Statement stmt = con.createStatement();
        ResultSet rs = stmt.executeQuery("SELECT * FROM library_students.book WHERE BookID=" + "'" + getBookID(borrowedBook)+ "'");
        if((rs.next())){
            copiesInBorrow=rs.getInt(11);
            availableCopies=rs.getInt(13);
        }
        pstmt = con.prepareStatement("UPDATE library_students.book SET CopiesInBorrow= ? AND AvailableCopies=? WHERE BookID=?");
        pstmt.setInt(1,++copiesInBorrow);
        pstmt.setInt(2,--availableCopies);
        pstmt.setString(3,getBookID(borrowedBook));
        pstmt.executeUpdate();
        rs.close();
        }catch (SQLException ex) {
            ex.printStackTrace();
        }
}

我没有收到任何错误,executeUpdate();也回来了1 有什么问题吗?

1 个答案:

答案 0 :(得分:1)

您遇到语法错误,请更改为:

UPDATE library_students.book SET CopiesInBorrow= ?, AvailableCopies=? WHERE BookID=?

在要更新的列之间不要使用AND。您可以在AND部分使用WHERE来应用所需的条件。

如果您想要这样的东西:

UPDATE library_students.book SET CopiesInBorrow= ? WHERE AvailableCopies=? AND BookID=?

然后使用AND是有效的。

从您的代码中,我看到您只想增加一列的值并减少另一列的值。您无需首先在表中找到这些值,然后进行更改。

您可以执行以下语句:

UPDATE library_students.book SET CopiesInBorrow = CopiesInBorrow + 1, AvailableCopies = AvailableCopies - 1 WHERE BookID = ?

因此更改为:

public void updateFields(BorrowedBook borrowedBook) throws SQLException {
    PreparedStatement pstmt;
    try {
        Statement stmt = con.createStatement();
        pstmt = con.prepareStatement("UPDATE library_students.book SET CopiesInBorrow = CopiesInBorrow + 1, AvailableCopies = AvailableCopies - 1 WHERE BookID = ?");
        pstmt.setString(1, getBookID(borrowedBook));
        pstmt.executeUpdate();
        rs.close();
    }catch (SQLException ex) {
        ex.printStackTrace();
    }
}