问题
I need to insert a string defined in Javascript into an MSSQL table.
This is what I have so far:
Javascript:
var message = "It's a great day today!";
$.post('www.server.com/message='+message, function(response){
console.log(response);
});
Node.js Server:
//..... 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 file):
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
Summary of what is going on:
- I am defining a message as string. (note that it contains an single quote)
- I am sending that string to the Node.js server
- I am using Node.js to send the string to mssql
The Problem: After learning more about Object Oriented Program, I have come to the realisation that the way I am performing the insert is highly frowned upon because It is open to SQL injection. Also, the code will break during the execution of the SQL query because of the single quote in the string.
The solution: According most resources I have found, the solution is to use "Prepared Statements".
My Issue:
How on earth do I convert what I have already done, to utilise prepared statements? I have searched the web for HOURS and I cannot find one good example of how to do a prepared statement with Node.JS for MSSQL (not MySQL) which is comprehensible for a beginner to Node.Js
回答1:
If you are using the Tedious cross-platform MSSQL driver implementation, the documentation is here: http://tediousjs.github.io/tedious/parameters.html
Basically you prepare a SQL statement with '@xxx' placeholders for values you need to inject, the you bind the actual values of those parameters to your request, then execute your request.
来源:https://stackoverflow.com/questions/46188407/how-do-i-create-a-prepared-statement-in-node-js-for-mssql