I have a database in SQL with a table named "Vehicle". It has a primary key as a VARCHAR. What I'm triying to do is validate whether the ID i'm entering is already registered. "plate" is my Primary Key.
This is my "Insert" method on Vehicle class:
int match = 0;
try {
String query = "insert into vehicle values ('"+this.plate+"','"+this.maker+"','"+this.model+"','"+this.color+"','"+this.year+"','"+ this.price+"') ";
state = con.createStatement();
match = state.executeUpdate(query);
return match;
} catch (SQLException ex) {
Logger.getLogger(Vehicle.class.getName()).log(Level.SEVERE, null, ex);
}
return match;
This is my "Insert" code on a Internal Frame:
String plate = txtPlate.getText().trim();
String model = txtModel.getText().trim();
String maker = txtMker.getText().trim();
String color = txtColor.getText().trim();
String year = txtYear.getText().trim();
String price = txtPrice.getText().trim();
if(plate.equals("") || maker.equals("") || model.equals("") || color.equals("") || year.equals("") || price.equals("") )
JOptionPane.showMessageDialog(rootPane, "Cant leave blank spaces");
else{
try {
int year = Integer.parseInt(year);
int price = Integer.parseInt(price);
Vehicle v1 = new Vehicle(plate, model, maker, color, year, price);
if (v1.insert() > 0)
{
JOptionPane.showMessageDialog(rootPane, "Register succes!");
}else
{
JOptionPane.showMessageDialog(rootPane, "Register failed");
}
}catch (NumberFormatException exc)
{
JOptionPane.showMessageDialog(this, "Error, insert numbers on 'YEAR and PRICE'");
}
}
I tried catching the an exception, but didn't work. Every time I add a repeated Plate(PK) my programs throws an exception, though I can't seem to use it.
This is a bit of the log after trying to add a vehicle with the same plate(PK)
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry 'ARP22' for key 'PRIMARY'
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)