private
void saveButtonActionPerformed(java.awt.event.ActionEvent evt) {
//
// retrieve and convert data
into local variables
//
String name =
nameField.getText();
String strquantity =
quantityField.getText();
String strcost =
costField.getText();
short quantity = 0;;
double cost = 0;
try{
quantity =
Short.parseShort(strquantity);
}
catch(NumberFormatException
e)
{
messageLabel.setText("Invalid entry in quantity field, must be a
number");
return;
}
try{
cost =
Double.parseDouble(strcost);
}
catch(NumberFormatException
e)
{
messageLabel.setText("Invalid entry in cost field, must be a number");
return;
}
//
// test data for consistency
and accuracy
//
if(cost < 0)
{
messageLabel.setText("Cost must be greater than or equal to zero");
return;
}
if(quantity < 0)
{
messageLabel.setText("Quantity must be greater than or equal to zero");
return;
}
if(name.length() <= 0)
{
messageLabel.setText("Name cannot be blank");
return;
}
//
// create and execute
PreparedStatement
//
try{
PreparedStatement prep = con.prepareStatement("INSERT INTO products
(Name, Quantity, Cost)
Values(?, ?, ?)");
prep.setString(1,name);
prep.setShort(2,quantity);
prep.setDouble(3,cost);
int result =
prep.executeUpdate();
if(result == 1)
messageLabel.setText(name+" added to the Products table");
else
messageLabel.setText("Unable to add "+name+" to Products table");
prep.close(); //
close the PreparedStatement
}
catch (SQLException e)
{
messageLabel.setText("Unable to add "+name+" to Products table :
"+e.getMessage());
}
}
|