web inserts at the same time

2019-07-20 02:53发布

问题:

We have developed an online quiz where users can register a team to take part in the quiz.

There is a check in the asp to see if that teamname has already been submitted, and if it has, an error is generated.

We have noticed a problem if 2 teams are registered at exactly the same time with the same name, that both teams are registered. Although this is highly unlikely, we wondered what approach should be used to overcome this.

We are using mySql as the database if that makes any difference.

Thanks for any guidance.

回答1:

Don't worry this never happens.

Databases are smart enough and handle concurrency isuuses.

If you run a query on database for registering a team and another team register at the same time, at database level the first query (when it's send to database) succeed and the second fails with an error which you should take care of. If registeration needs actions more than a simple insert on a table then you should use transaction objects at your queries/store-procedures.



回答2:

You can set the name column to be unique, and the database will throw an error on the second insert. If you want to do it in code, it will be more complicated.



回答3:

Not sure how two teams can register at exactly the same time - even if the requests are submitted simultaneously (down to the nanosecond), your transaction semantics should still guarantee that one of them is "first" from the database point of view.