I want to validate a data that is to be inputed into the db to check if there are muliple entries

I am trying to write a code that allows users using the scanner to input the details of student and using JDBC to connect it to the database.
I have my student_id set as the Primary key in the database but that will just throw an error if the user inputs the same student_id again.

There are two options I am thinking of, is there a way I can catch the particular error of primary key already exists so i can just tell the user that the id exists or I can write a code to validate that by checking for in the db if the id provided is already present in the ID

This is my current code

System.out.println("Provide your student ID");
int student_id = scanner.nextInt();
scanner.nextLine();
System.out.println("Provide your first_name");
String first_name = scanner.nextLine();
System.out.println("Provide your last_name");
String last_name = scanner.nextLine();
System.out.println("Provide your level");
int level = scanner.nextInt();
try {
  stmt.setInt(1, student_id);
  stmt.setString(2, first_name);
  stmt.setString(3, last_name);
  stmt.setInt(4, level);
  stmt.addBatch();  //this adds the code above as a batch
  stmt.clearParameters();
  i++; // increment in the loop so it does not become an infinite loop
  stmt.executeBatch();
} catch (BatchUpdateException e) {
  System.out.println("student_id provided already exist");
}

This works but I want to breakdown the exception more to only print out the error message student_id already provided only when that is the error. Note the error that causes this is sqlintegrityconstraintviolationexception. And right now any error that occurs in my batch it will tell the user that the error is due to sqlintegrityconstraintviolationexception

And also I am open to how to do the second option of validating rather than try and catch

  • 1

    Please edit the post and format the code properly.

    – 

  • 1

    I formatted your code for you, but next time, please take the time to do it yourself.

    – 

  • Upsert

    – 

Leave a Comment