I have the following code to update a record. The code compiles however it skips everything in the try statement and displays the error message in the catch statement. I am not sure what it is that I am missing as it doesn’t display any sort of syntax error.
try {
PreparedStatement st = db.con.prepareStatement("UPDATE item SET Name = ?, Size = ?, Price = ?, WHERE ItemCode = ?");
st.setString(1, textArea_Code.getText());
st.setString(2, textArea_name.getText());
st.setString(3, textArea_size.getText());
st.setString(4, textArea_price.getText());
st.executeUpdate();
JOptionPane.showMessageDialog(frame, "Updated");
} catch (SQLException e ) {
JOptionPane.showMessageDialog(frame, "update not successful");
}
You’re swallowing the exception, which is generally a bad idea. At the very least call
e.printStackTrace()so that you have an output of the exception.As it happens, you have a syntax error in your SQL statement:
UPDATE item SET Name = ?, Size = ?, Price = ?, WHERE ItemCode = ?– remove the comma from afterPrice = ?.To address the confusion about why the UPDATE statement still doesn’t work, despite fixing the syntax error, allow me to explain in more detail (far easier to do this in the answer, rather than in comments).
The
?character in your SQL String is a placeholder for a value that you’ll set with one of the variousset_()methods (in your case, only eversetString(). Each placeholder is numbered with an index starting from 1 – the first?that appears in your string represents index 1, the second represents index 2, etc.Your SQL string looks like this:
You’re setting values for your placeholders like this: