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

时间:2019-02-16 10:52:44

标签: javascript mysql discord.js

如何检查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 

1 个答案:

答案 0 :(得分:0)

问题在于,当resultbu[0]有时(是)为空数组时,您引用的是resultbu,因此resultbu[0].builduhcelo不可能并触发错误。

其次,您将嵌套一次完成的查询。选择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)
    }
})