Search code examples
javascriptmysqlnode.jsdiscord.jsmysql2

Discord.js and mysql2 error on INSERT method


I am currently programming a Discord bot with mysql. And then I tried to make a vote system with mysql2 but there is always an error in the console and I don't know what I'm doing wrong. Can anyone helps me? I'll tried all what i can but all of that what i make is false

(Packages that i use: discord.js, mysql2, sequelize code:

/**
 * 
 *          vote System
 * 
 */
const timeout = new Set();
const ctime = 86400;
client.on('message', async message => {
  connection.query(
    `SELECT * from \'vote'`
  )

  var voteData = {
    data: [
      {
      "username:": message.author.username,
      "guild_id:": message.guild.id,  
      "guild_name": message.guild.name,
      "votes": "1"
    }
    ],
};
  if(message.content.includes(`${config.prefix}vote`)) {
    if(timeout.has(message.guild.id)){
      return message.channel.send(`Es wurde heute bereits gevotet!`)
    }
    let embed = new Discord.MessageEmbed()
    .setAuthor(`${message.author.tag}`, message.author.avatarURL({format: "webp", size: 128}))
    .setTitle(`Server & Bot Vote!`)
    .setDescription(`Sie haben erfolgreich Gevotet!\n Es kann in 24 Stunden erneut gevotet werden!`)
    .setTimestamp()
    .setColor('GREEN')
    .setFooter(message.author.tag, message.author.avatarURL({format: "webp", size: 128}))
    message.channel.send(embed)
    message.delete({reason: 'Timeouted!'})
    let vote = vote;
    let guildId = guildId;
    let username = username;
    const connection = mysql.createPool({
      host: 'localhost',
      user: 'root',
      database: 'rpd-bot'
  });
    /*fs.writeFile('./votes.json', JSON.stringify(voteData, null, 1), function (err) {
        if(err) throw err;*/
        console.log(colors.green('Datensatz hinzugefügt!'))
        connection.query(`SELECT * FROM rpd-bot`)
        connection.promise()
        .execute("INSERT INTO `vote`(`guildId`, `date`, `username`) VALUES (552,21.10,'test')")
    timeout.add(message.guild.id)
    setTimeout(() => {
      timeout.delete(message.guild.id)
    }, ctime * 1000);
    if('errno: 1064') {
      console.log(error)
    }
  }
})

Error in my Console:

(node:27128) UnhandledPromiseRejectionWarning: ReferenceError: Cannot access 'vote' before initialization

(node:27128) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
events.js:292
      throw er; // Unhandled 'error' event
      ^

Error: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''vote'' at line 1

    [... lines matching original stack trace ...]
    at Socket.Readable.push (_stream_readable.js:212:10)
    at TCP.onStreamRead (internal/stream_base_commons.js:186:23) {
  code: 'ER_PARSE_ERROR',
  errno: 1064,
  sqlState: '42000',
  sqlMessage: "You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''vote'' at line 1"
}

Solution

  • You're using the wrong quotes:

    connection.query(
      'SELECT * from `vote`'
    )
    

    See the manual on how to escape schema and column names properly.

    Due to conflicts between JavaScript template strings and SQL escaping quotes it's best to use single quotes for JavaScript strings. Thus:

    'SELECT "x", `y` FROM `z`'
    

    Here both quote styles are fine and don't interfere with the overall string.