check for duplicate data before insert

后端 未结 3 1739
悲&欢浪女
悲&欢浪女 2020-12-22 12:29

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

3条回答
  •  清酒与你
    2020-12-22 12:59

    There is a choice for

    • INSERT IGNORE ("IF NOT EXISTS")
    • INSERT ON DUPLICATE KEY UPDATE

    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
    

提交回复
热议问题