Node.js API-选择逗号分隔字符串中多个值的位置

时间:2018-06-30 18:51:09

标签: javascript mysql sql node.js

我有这个api(带有node.js和mysql):

localhost:4001/api/?id=555,666
localhost:4001/api/?id=555

在选择项中,我正在检查参数是否具有这样的逗号(','):

...
if (id.includes(",")) {     
    return `${field} IN (?);` 
} else {
    return `${field} = ?`
} 
...

...以获得这样的结果:

SQL: "SELECT * FROM table WHERE id IN (555,666)"
SQL: "SELECT * FROM table WHERE id=555;"

如果我过滤固定值,效果很好。但是,像过滤一样呢?

例如如果我过滤多个名称,则执行以下操作:

localhost:4001/api/?name=money,invest,stocks
localhost:4001/api/?name=money,invest
localhost:4001/api/?name=money

...
if (name.includes(",")) {       
    return `${field} IN (?)` 
} else {
    return `${field} LIKE ?`
} 
...

Result:

SQL: "SELECT * FROM table WHERE name IN (money,invest,stocks)"  
SQL: "SELECT * FROM table WHERE name IN (money,invest)"
SQL: "SELECT * FROM table WHERE name LIKE money;"   

...但是我想拥有的是这个

Goal:

SQL: "SELECT * FROM table WHERE name LIKE '%money%' OR name LIKE '%invest%' OR name LIKE '%stocks%';"   
SQL: "SELECT * FROM table WHERE name LIKE '%money%' OR name LIKE '%invest%';"
SQL: "SELECT * FROM table WHERE name LIKE money;"

我该如何更改查询?

1 个答案:

答案 0 :(得分:0)

这里是一个示例,但请阅读以下有关SQL注入的注意事项:

var name = "money,invest,stocks";

var str = "SELECT * FROM table WHERE ";

if (name.includes(",")) {  
  var names = name.split(",");
  names.map((o,i)=>{
    str += "name LIKE '%"+o+"%' ";
   (i==names.length -1)?str += "":str += "OR ";

  }) 
} else{
  str += "name LIKE '%"+name+"%' ";
}

console.log(str);

您可以使用.split()将字符串转换为数组,并使用.map()迭代新数组。


我不知道您使用的是什么驱动程序,但是如果您像上面的示例一样粘贴查询,则您的代码暴露给SQL Injection ,暴露给prevent this,您应该使用prepared statements。因此,如果您在nodejs中使用 mysql 库,则示例如下所示:

var name = "money,invest,stocks";

var str = "SELECT * FROM table WHERE ";

if (name.includes(",")) {  
  var names = name.split(",");
  names.map((o,i)=>{
    names[i] = '%'+o+'%'; 
    str += "name LIKE ? ";
   (i==names.length -1)?str += "":str += "OR ";

  }) 
} else{
  str += "name LIKE ? ";
}

console.log(str);//SELECT * FROM table WHERE name LIKE ? OR name LIKE ? OR name LIKE ?
console.log(names);//[ '%money%', '%invest%', '%stocks%' ]

在查询中,您应该像这样将所有参数作为数组传递(在这种情况下为名称):

connection.query(str,names,function(err,rows){
    //connection.release();
    if(!err) {
      //further code
      }
    });