I'm trying to prevent an SQL Injection in my Node.js Backend. I'm using the mssql package, i was doing some tests and i found that if in a parameter there's the character ' the query doesn't work (obviously).
sql.connect(sqlConfig, function (err) {
str_query = 'SELECT * FROM table WHERE notes= '+req.query.notes+'';
if (err) console.log(err);
var request = new sql.Request();
// query to the database and get the records
request.query(str_query, function (err, recordset) {
//here do things
}
How i can prevent this ?
This is untested but here's how I would do it.
Here's a bit of information about what's going on from google.
Parameterized queries force the developer to first define all the SQL code, and then pass in each parameter to the query later. This coding style allows the database to distinguish between code and data, regardless of what user input is supplied.
sql.connect(sqlConfig, function (err) {
str_query = 'SELECT * FROM table WHERE notes=?';
if (err) console.log(err);
var request = new sql.Request();
// query to the database and get the records
request.query(str_query, [req.query.notes] , function (err, recordset) {
//here do things
}