Home > Back-end >  I can't update SQL by Java
I can't update SQL by Java

Time:06-23

I'm trying to update a value in a MySQL database with this code.

public static void editProduct(ProductDB x) {
    try
    {
      String query = "UPDATE products SET product_name = ? , price_per_unit = ? , product_description = ? , product_image  = ? WHERE product_id = ?";
      PreparedStatement st = conn.prepareStatement(query);        
      st.setString(1, x.product_name);
      st.setDouble(2, x.price_per_unit);
      st.setString(3, x.product_description);     
      if(x.product_image != null) {
          System.out.println("xx");
          ByteArrayOutputStream baos = new ByteArrayOutputStream();
          ImageIO.write(x.product_image , "png" , baos);
          byte [] buffer = baos.toByteArray();
          st.setBytes(4, buffer);         
      }else {
          byte [] buffer = new  byte[0];
      st.setBytes(4, buffer);
      }
      st.setInt(5, x.product_id);         
      st.executeUpdate();
      st.close();
      System.out.println("xxx");
    }
    catch (Exception e)
    {
      System.err.println("Got an exception! ");
      System.err.println(e.getMessage());
    }
}

and

    public void actionPerformed(ActionEvent e) {
        ProductDB x = new ProductDB(0, textField_ProductName.getText().trim(),
                Double.parseDouble(textField_productPrice.getText().trim()),
                textField_ProductDescription.getText().trim(), (BufferedImage) imagePanel.getImage());
        ProductManager.editProduct(x);
        load();
        
        JOptionPane.showMessageDialog(ProductFrmae.this , "Edited");
        
    }
});

Code printed "xx" and "xxx" and no exception caught.

And it already have "Edited" pop up.

What did I do wrong?

CodePudding user response:

What is the value of i if you do this? It should give you the number of rows affected. int i=st.executeUpdate();

  • Related