我需要将 Javascript 中定义的字符串插入到 SQL 表中。
这是我到目前为止所拥有的:
JavaScript:
var message = "It's a great day today!";
$.post('www.server.com/message='+message, function(response){
console.log(response);
});
Node.js 服务器:
//..... a bunch of code has been used to accept the HTTP request and get the message...
// for the purpose of this example, the message is asigned to 'NodeMsg'
var mssqldb = require("../core/mssql");
var NodeMsg = theMessageReceivedFromHTTPRequest;
function saveMessage(message) {
mssqldb.executeMssql("insert into messages (message, status) VALUES('"+message+"', 'new')", function (err) {
if (err) {
httpMsgs.show500(req, resp, err);
}//end if
else {
httpMsgs.sendJson(req, resp, 'success');
}//end else
});
};
mssql.js(node.js 文件):
var mssqldb = require("mssql");
var settings = require("../settings");
exports.executeMssql = function(sql, callback) {
var conn = new mssqldb.Connection(settings.mssqlConfig);
conn.connect()
.then(function(){
var req = new mssqldb.Request(conn);
req.query(sql)
.then(function (recordset) {
callback(recordset);
})
.catch(function(err){
console.log(err);
callback(null, err);
});
})
.catch(function(err){
console.log(err);
callback(null, err);
});
};//end executeMssql
正在发生的事情的摘要:
- 我将消息定义为字符串。 (注意它包含单引号)
- 我将该字符串发送到 Node.js 服务器
- 我正在使用 Node.js 将字符串发送到 mssql
问题:在了解了有关面向对象程序的更多信息后,我意识到我执行插入的方式是非常不受欢迎的,因为它对 SQL 注入是开放的。此外,由于字符串中存在单引号,代码会在执行 SQL 查询期间中断。
解决方案:根据我找到的大多数资源,解决方案是使用“准备好的语句”。
我的问题:
我究竟如何转换我已经完成的内容,以利用准备好的语句?我在网上搜索了几个小时,但找不到一个很好的例子来说明如何使用 Node.JS for MSSQL(而不是 MySQL)执行准备好的语句,这对于 Node.Js 的初学者来说是可以理解的