我想将一个对象传递给 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/