如果已经存储了这样的唯一值,如何重新尝试插入数据库

How to reattempt inserting into database if there was already such unique value stored

我搜索了任何现有模式,但没有找到任何东西。

所以,问题是我想在我的 MySQL 数据库中存储一些 key 值,这将是 唯一的 。我像这样在服务器端生成它:

var pc = require('password-creator');
var key = pc.create(20); //  "f9Wp>=\qJqx]rwwbbiQ8

然后我将它发送到数据库:

 connection.query(db_query, function (err, rows, fields) {
    if(err){
        if(err.code == "ER_DUP_ENTRY"){
            // here I could attempt again with newly generated key by
            // calling another query to database but this is giving me 
            // a limited amount of such attempts
        }
    }
    else{
        // there was no duplicate
    }
});

所以一切似乎都很好,但有很小的可能性 ER_DUP_ENTRY。现在是我的问题:

如何正确解决这种情况?我的意思是我总是想在数据库中输入一些 key 值。我想到了循环,但这感觉很愚蠢,因为它是对数据库的异步查询。在这种情况下,我基本上是在寻找正确的方法。

这应该像将生成唯一值并插入代码块包装到一个函数中一样简单,如果出现重复键,您可以重新调用:

function tryToStoreUnique()
{
    var db_query = buildDbQuery(pc.create(20));
    connection.query(db_query, function (err, rows, fields) {
    if(err) {
        if(err.code == "ER_DUP_ENTRY"){
           // you can add counter to avoid lock if most of unique space is occupied
           tryToStoreUnique();
        }
    }
    else{
        // there was no duplicate
    }
  });
}