I am currently using Java to try to INSERT a customer in my Database:
public void saveCustomer(Customer c) {
getConnection();
try {
CallableStatement pstmt = con.prepareCall("{call sp_saveCustomer(?,?)}");
pstmt.setString(1, c.getName());
pstmt.setString(2, a.getLastName());
pstmt.executeUpdate();
closeConnection();
} catch (SQLException e) {
// Handle Exception
}
}
When a user tries to INSERT a duplicate record, the catch block will trigger. What I’m worried about is that I don’t know if this means a performance hit. Isn’t a better way to check if a customer already exists? Something like:
public void saveCustomer(Customer c) {
getConnection();
boolean exists = false;
CallableStatement pstmt = con.prepareCall("{call sp_checkCustomerExistence(?,?)}");
pstmt.setString(1, c.getName());
pstmt.setString(2, a.getLastName());
ResultSet rs = pstmt.executeQuery();
if (rs.next()) exists = true;
if ( exists ){
closeConnection();
return;
}
CallableStatement pstmt = con.prepareCall("{call sp_saveCustomer(?,?)}");
pstmt.setString(1, c.getName());
pstmt.setString(2, a.getLastName());
pstmt.executeUpdate();
closeConnection();
}
What would be the best solution based on the best performance? Should I check myself if the customer exists or should I let the Exception be thrown?
I think checking the duplicate is preferable than catching the exceptions. Only suggestion I have it to perform the check in your procedure itself if you can i.e. create a procedure as
sp_check_and_save_customerwhich will check for duplicate and save if it doesn’t already exist. This way there will be very less time difference between the check and insert, which becomes more crucial in heavy loaded applications.Still, please have your exception handling as well as it is still possible that another process inserts the data in between the check and insert.