使用Node显示SQL值

时间:2017-04-25 23:42:10

标签: javascript mysql sql node.js

我正在使用Node.js创建Discord Bot。我希望在用户键入!commands all时显示所有自定义命令,表格如下所示

| | guildname | guildid | commandname | commandreply | username | userid
------------------------------------------------------------------------
| | MyServer    1002      !test         This is test   Rusty      890

我有这段代码:

var info = {
  "guildname": message.guild.name,
  "guildid": message.guild.id,
  "commandname": args[0],
  "commandreply": args.join(" ").slice(args[0].length),
  "username": message.author.username,
  "userid": message.author.id
}

connection.query("SELECT * FROM commands WHERE guildid = '" + message.guild.id + "'", info, function(error, commandExists) {
  if (error) throw error;

  if (commandExists.length) {
    console.log(commandname); // commandname is not defined
  }
}

如何访问其中一个值,例如commandname?

1 个答案:

答案 0 :(得分:3)

results将包含一个对象数组,其中每个对象将包含所选字段及其值。

connection.query("SELECT * FROM commands WHERE guildid = '" + message.guild.id + "'", info, (error, results, fields) => {

    // error will be an Error if one occurred during the query 
    // results will contain the results of the query 
    // fields will contain information about the returned results fields (if any) 

    if (error) throw error;

    if (results.length) {
        results.forEach(command => {
            console.log(command.commandname);
        });
    }
});

可以使用placeholders来改进查询。

如果您正在使用mysqlmysql2,请按照以下方式进行操作:

connection.config.queryFormat = function (query, values) {
  if (!values) return query;
  return query.replace(/\:(\w+)/g, function (txt, key) {
    if (values.hasOwnProperty(key)) {
      return this.escape(values[key]);
    }
    return txt;
  }.bind(this));
};

connection.query("SELECT * FROM commands WHERE guildid = :guildId", { guildId: message.guild.id });

检查此问题:

How can prepared statements protect from SQL injection attacks?

修改

在mysql2中,内置支持named placeholders.