我正在使用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?
答案 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来改进查询。
如果您正在使用mysql或mysql2,请按照以下方式进行操作:
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.