I\'m creating a java swing program where users can create a record, but I want to be able to check for duplicates before allowing the users to create the record. Here\'s my
If you want DutyName
and volNric
to have unique values, then do so with a unique constraint/index:
create index idx_assignrequests_dutyname_volnric on assignrequests(dutyname, volnric);
Then, when you do the insert
, you can let it fail. Or, you can just ignore it using on duplicate key update
:
INSERT into assignrequests(reqId, dutyName, volNric)"
VALUES ('" + id + "','" + dutyName + "','" + volNric + "')
ON DUPLICATE KEY UPDATE dutyName = VALUES(dutyName);
The column being updated is being set to itself -- so the operation doesn't do anything.
I am completely agree with the @hd1 answer you need to apply this condition for the query after creating the unique constraint.
You need to create unique constraint first to any of your column that you need as a unique column.
EXCEPTION
WHEN DUP_VAL_ON_INDEX THEN
DBMS_OUTPUT.PUT_LINE('This is duplicate Value ')
There is a choice for
In the CREATE TABLE there must be a constraint, unique key on the unique fields. Otherwise ALTER TABLE.
I leave it to you to make a choice and inspect the mysql reference documentation.
I assume reqId
is an AUTOINCREMENT primary key.
In the INSERT leave it out, to be generated by the database, in order to not have concurrency problems, of two people at the same time getting a new reqId.
Furthermore use PreparedStatement; this is really almost obligatory, as it escapes apostrophe and backslashes; prevents SQL injection, looks better.
try (PreparedStatement stm = conn.prepareStatement(
"INSERT IGNORE INTO assignrequests (dutyName, volNric) VALUES(?, ?)")) {
stm.setString(1, dutyName);
stm.setString(2, volNric);
int updateCount = stm.executeUpdate();
if (updateCount != 0) {
try (ResultSet genKeys = stm.getGeneratedKeys()) {
if (genKeys.next()) { // At most 1 record inserted
// Normally only one key generated per record.
int reqId = genKeys.getInt(0);
...
}
} // Close result set.
}
} // Closes stm