javascript - 我们可以将对象作为参数传递到类似sql的数组中,以防止使用promise-mysql模块在nodejs中进行sql注入(inject)吗

标签 javascript mysql sql node.js

我想将一个对象传递给 SQL 查询。

我知道这有效:

connection.query('SELECT * FROM projects WHERE status = ?',
    ['active']
)

使用命名对象属性作为参数的正确语法是什么?像这样的事情:

connection.query('SELECT * FROM projects WHERE status = :status ',
    { status: 'active' }
)

最佳答案

这种可能性不是开箱即用的,但documentation mysqljs(promise-mysql 所依赖的)的 解释了如何通过将自定义函数分配给 connection.config.queryFormat 来实现这一点:

If you prefer to have another type of query escape format, there's a connection configuration option you can use to define a custom format function. You can access the connection object if you want to use the built-in .escape() or any other connection function.

Here's an example of how to implement another format:

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("UPDATE posts SET title = :title", { title: "Hello MySQL" });

关于javascript - 我们可以将对象作为参数传递到类似sql的数组中,以防止使用promise-mysql模块在nodejs中进行sql注入(inject)吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55234259/

相关文章:

mysql - 创建存储过程时遇到问题

计算值上的 MySQL GROUP BY 给出错误 - 使用其他值会产生意外结果

sql - 按 MS Access 中的连续日期分组

javascript - WYMeditor 不会将内容反射(reflect)到 textarea 值中

javascript - 使用 javascript 进行 SUM 动态输入字段 onchange

javascript - 网络音频的分贝值

java - 需要用hibernate dao实现方法保存两个来自不同jsp页面的有外键关系的表

javascript - 使用javascript提取起始字符串和结束字符串之间的字符串

PHP 在 mysql 查询上参数化,在部分字符串上使用 LIKE 和 CONCAT

相当于 != 的 sql 运算符