1.

Detecting Duplicate Keys I Have A Program That Inserts Rows In A Table. My Table Has A Column 'name' That Has A Unique Constraint. If The User Attempts To Insert A Duplicate Name Into The Table, I Want To Display An Error Message By Processing The Error Code From The Database. How Can I Capture This Error Code In A Java Program?

Answer»

A solution that is perfectly portable to all databases, is to execute a query for checking if that UNIQUE value is present before inserting the row. The big advantage is that you can handle your error message in a very SIMPLE way, and the obvious DOWNSIDE is that you are going to use more time for inserting the record, but since you're working on a PK field, performance should not be so bad.

You can also get this information in a portable way, and potentially avoid ANOTHER database access, by capturing SQLState messages. Some databases get more SPECIFIC than others, but the general code portion is 23 - "Constraint Violations". UDB2, for example, gives a specific such as 23505, while others will only give 23000.

A solution that is perfectly portable to all databases, is to execute a query for checking if that unique value is present before inserting the row. The big advantage is that you can handle your error message in a very simple way, and the obvious downside is that you are going to use more time for inserting the record, but since you're working on a PK field, performance should not be so bad.

You can also get this information in a portable way, and potentially avoid another database access, by capturing SQLState messages. Some databases get more specific than others, but the general code portion is 23 - "Constraint Violations". UDB2, for example, gives a specific such as 23505, while others will only give 23000.



Discussion

No Comment Found