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
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