检查uuid(在数据库中)是否存在

Check if a uuid (in the database) exists

如何检查 MySQL 数据库中是否存在数据?我已经设法获取了数据,但我只想知道该怎么做:如果该数据不存在。

我当前的代码:

connection.query(`select builduhcelo from practiceplayers where uuid = '${uuid}'`, function (errbu, resultbu) {
    if(errbu) throw errbu;
    connection.query(`select nodebuffelo from practiceplayers where uuid = '${uuid}'`, function (errnd, resultnd) {
        if(errnd) throw errnd;
        connection.query(`select ironbuilduhcelo from practiceplayers where uuid = '${uuid}'`, function (erribu, resultibu) {
            if(erribu) throw erribu;
            let embed = new Discord.RichEmbed()
                .setAuthor(`Elorion.net`, `https://image.noelshack.com/fichiers/2019/06/7/1549795460-logo-elorionnetwork.png`)
                .setColor(color.elorion)
                .addField("Username", username)
                .addField("UUID", uuid)
                .addField("BuildUHC Elo", resultbu[0].builduhcelo)
                .addField("NoDebuff Elo", resultnd[0].nodebuffelo)
                .addField("IronBuildUHC Elo", resultibu[0].ironbuilduhcelo)
                .addField("Skin", `[Download](https://crafatar.com/skins/${uuid}.png)`)
                .setThumbnail(`https://crafatar.com/avatars/${uuid}.png?size=400&overlay=true`)
                .setFooter(`Ⓒ Elorion.net 2019. All rights reserved`);
            message.channel.send(embed)
        })
    })
})

当数据库中不存在 uuid 时,我收到此错误:

throw err; // Rethrow non-MySQL errors 
^ 

TypeError: Cannot read property 'builduhcelo' of undefined 

问题是您引用 resultbu[0]resultbu 将(有时)是一个空数组,因此 resultbu[0].builduhcelo 不可能并触发错误。

其次,您嵌套了本可以一次性完成的查询。 Select 您的 SQL 查询中的所有三列。

最后,添加一个if条件来验证result数组不为空:

connection.query(`select builduhcelo, nodebuffelo, ironbuilduhcelo 
                  from practiceplayers 
                  where uuid = '${uuid}'`, function (err, result) {
    if (err) throw errbu;
    if (result.length) { /* Only execute the rest when there is a match: */
        let embed = new Discord.RichEmbed()
            .setAuthor(`Elorion.net`, `https://image.noelshack.com/fichiers/2019/06/7/1549795460-logo-elorionnetwork.png`)
            .setColor(color.elorion)
            .addField("Username", username)
            .addField("UUID", uuid)
            .addField("BuildUHC Elo", result[0].builduhcelo)
            .addField("NoDebuff Elo", result[0].nodebuffelo)
            .addField("IronBuildUHC Elo", result[0].ironbuilduhcelo)
            .addField("Skin", `[Download](https://crafatar.com/skins/${uuid}.png)`)
            .setThumbnail(`https://crafatar.com/avatars/${uuid}.png?size=400&overlay=true`)
            .setFooter(`Ⓒ Elorion.net 2019. All rights reserved`);
        message.channel.send(embed)
    }
})