I a developing a REST API with Node.js, using AWS Lambda and API Gateway. I am using MySQL database. I am a Java guy and very new to Node.JS. Just one day old.
I realised that there are multiple ways to prevent SQL INjection in Node.js. Below is my code
const mysql = require('mysql');
const PropertiesReader = require('properties-reader');
const prop = PropertiesReader('properties.properties');
const con = mysql.createConnection({
host : prop.get('server.host'),
user : prop.get("server.username"),
password : prop.get("server.password"),
port : prop.get("server.port"),
database : prop.get("server.dbname")
});
exports.getRoleByID = (event, context, callback) => {
const { id } = event.queryStringParameters;
console.log("id", id);
// allows for using callbacks as finish/error-handlers
context.callbackWaitsForEmptyEventLoop = false;
const sql = "select * from role where idrole = ?";
con.query(sql, [id], function (err, result) {
if (err) throw err;
var response = {
"statusCode": 200,
"headers": {
"Content-Type": "application/json"
},
"body": JSON.stringify(result),
"isBase64Encoded": false
};
callback(null, response)
});
};
As you can see, I am using ? to apply the SQL Injection protection. But I also noticed that doing something like this will give the protection
var sql = 'SELECT * FROM users WHERE id = ' + connection.escape(userId);
Which way is used to protect the code from SQL Injections? The way I used or the connetion.escape() way? Or some other way?