Home > Article > Backend Development > mysql insert problem
Two users insert a piece of data at the same time,
insert into table set name='tom',num=2
insert into table set name='jack',num=2
, but the business logic does not allow the num value to appear repeatedly.
How to restrict MySQL from inserting duplicate data?
1. Add a joint unique index, but the program will report an error, which seems unfeasible.
Is there any other method?
Two users insert a piece of data at the same time,
insert into table set name='tom',num=2
insert into table set name='jack',num=2
, but the business logic does not allow the num value to appear repeatedly.
How to restrict MySQL from inserting duplicate data?
1. Add a joint unique index, but the program will report an error, which seems unfeasible.
Is there any other method?
Use a unique index, use transaction processing in the insertion scenario, and throw a transaction reminder if there is a duplicate value.
The program reports an error?
You just need to catch the corresponding exception, then return and make a business explanation.
insert ignore
Can’t you?
That is, before each insertion, you have to check whether the num field in the table contains the value to be inserted; and consider the concurrency situation. Right? Either use mysql transactions; or mysql lock table mechanism
It is recommended that the database have its own verification mechanism, just like your unique constraint or index. The application can capture the error information of the database and provide corresponding explanations.