I can update data properly using Java Swing and MySQL. If id
is present in the database JOptionPane
shows a dialog box that Updated data Succesfully and even id
is not present in the database JOtionPane
shows the same dialog box. How to solve that?
private void btnUpdateActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/inventoryms", "root", "");
Statement stmt = conn.createStatement();
String query = "update inventory set name = '" txtName.getText() "', price = '" txtPrice.getText() "', category = '" comboCat.getSelectedItem().toString() "' where id = '" txtId.getText() "' ";
stmt.executeUpdate(query);
JOptionPane.showMessageDialog(null,"Data updated successfully!!");
conn.close();
}
catch(Exception ex){
JOptionPane.showMessageDialog(null, "Error is: " ex);
}
}
Show the same dialog box that updated data successfully.
CodePudding user response:
The comment, by @prasad_, to your question, is the answer. Method executeUpdate returns the number of rows affected by your UPDATE statement. Note that it is not an error if the UPDATE statement does not update any rows.
Apart from that, note the following:
- Since Java 6, you no longer need to explicitly load the JDBC driver class via Class.forName.
- You should use PreparedStatement (rather than
Statement
). - You should also close the
PreparedStatement
and theConnection
which you can do via try-with-resources. - You can use text blocks to make your SQL more readable.
- You should catch the exception that the method throws which, in your case, is
SQLException
and you should print the stack trace in order to help find the cause of the exception. - Note that the message displayed by JOptionPane can be any object and does not have to be a string.
private void btnUpdateActionPerformed(java.awt.event.ActionEvent evt) {
String query = """
update inventory
set name = ?
,price = ?
,category = ?
where id = ?
""";
try (Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/inventoryms", "root", "");
PreparedStatement stmt = conn.prepareStatement(query)) {
stmt.setString(1, txtName.getText());
stmt.setString(2, txtPrice.getText());
stmt.setString(3, comboCat.getSelectedItem().toString());
stmt.setString(4, txtId.getText());
int count = stmt.executeUpdate(query);
String msg = count > 0 ? "Data updated successfully!!" : "No changes.";
JOptionPane.showMessageDialog(null, msg);
}
catch (SQLException ex) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
ex.printStackTrace(pw);
JTextArea textArea = new JTextArea(sw.toString());
JScrollPane scrollPane = new JScrollPane(textArea);
JOptionPane.showMessageDialog(null, scrollPane, "ERROR", JOptionPane. ERROR_MESSAGE);
}
}
Refer to javadoc of JOptionPane
.