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 有什么问题吗?
答案 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();
}
}