How to input a NodeJS variable into an SQL query

泪湿孤枕 提交于 2019-11-29 07:44:30

You will need to put the value of the variable into the SQL statement.

This is no good:

"SELECT * FROM arrivals WHERE flight = 'flightNo'"

This will work, but it is not safe from SQL injection attacks:

"SELECT * FROM arrivals WHERE flight = '" + flightNo + "'"

To be safe from SQL injection, you can escape your value like this:

"SELECT * FROM arrivals WHERE flight = '" + connection.escape(flightNo) + "'"

But the best way is with parameter substitution:

app.get("/arrivals/:flightNo", cors(), function(req, res) {
  var flightNo = req.params.flightNo;

  var sql = "SELECT * FROM arrivals WHERE flight = ?";
  connection.query(sql, flightNo, function(err, rows, fields) {
  });
});

If you have multiple substitutions to make, use an array:

app.get("/arrivals/:flightNo", cors(), function(req, res) {
  var flightNo = req.params.flightNo;
  var minSize = req.query.minSize;

  var sql = "SELECT * FROM arrivals WHERE flight = ? AND size >= ?";
  connection.query(sql, [ flightNo, minSize ], function(err, rows, fields) {
  });
});

If you are using > ES6 :

connection.query(`SELECT * FROM arrivals WHERE flight = ${flightNo}`, function(err, rows, fields) {

If you are < ES6 :

connection.query("SELECT * FROM arrivals WHERE flight = " + flightNo, function(err, rows, fields) {

Please note that this is VERY BAD practice as you will be vulnerable to SQL-injection attacks.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!