How to avoid inserting duplicate data in Mysql

One, the problem

Requirement: When inserting data into the mysql database, first determine whether there is the data in the database, if there is, then give up, if not, then insert.

Data data = dataMapper.getByDataId(dataId);
if(data == null){
    dataMapper.insert(data1);
}

Problem: The following problems exist in concurrent requests:

1. Thread A queries data data1, and if it finds none, insert data1;

2. Before thread A successfully inserts data1, thread B queries data data1, and if it finds none, insert data1;

3. In this way, if thread A and thread B insert data1 successively, there are two data1 in the library.

Two, solve

Set the dataId parameter as a unique key.

In Navicat, select the table, right-click -> Design Table -> Index, the field is the parameter, and the index type is Unique.

Example: id is an auto-incrementing primary key, name is a unique key

CREATE TABLE `student` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(20) NOT NULL,
  `age` int(11) DEFAULT NULL,
  `sex` tinyint(4) DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `name_UNIQUE` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;


 

Guess you like

Origin blog.csdn.net/wishxiaozhu/article/details/102800521