node-mysql Using array in query

孤者浪人 提交于 2019-12-08 06:19:31

问题


I'm trying do a query using an array but having a parse error.

a - contains an array

Ex:[ 7, 26, 87, 65, 86, 23, 63, 69, 44, 61, 8, 79, 47, 88, 15, 17 ]

conexao_bd.escape(a) - escaped array

Ex: 7, 26, 87, 65, 86, 23, 63, 69, 44, 61, 8, 79, 47, 88, 15, 17

It needs to be in this format (7, 26, 87, 65, 86, 23, 63, 69, 44, 61, 8, 79, 47, 88, 15, 17), so I can use it in the query. Any help how to change format?

Code

conexao_bd.query("SELECT question, answer FROM ", conexao_bd.escape(tipo) + " WHERE id IN " + conexao_bd.escape(a) ,function(err, rows){

    if(err) console.log("Erro na query questions: "+err);
    else{
        perguntas.questions.push(rows);
        console.log(JSON.stringify(perguntas));
    }
});

回答1:


Look into Array.join() to return it as a string. This is a basic javascript question, not node related.




回答2:


There is an error on query

conexao_bd.query("SELECT question, answer FROM ", 

should be

conexao_bd.query("SELECT question, answer FROM "+



回答3:


I Actually found the correct Answer including Escaping (to prevent SQL Injection):

Nested arrays are turned into grouped lists (for bulk inserts), e.g. [['a', 'b'], ['c', 'd']] turns into ('a', 'b'), ('c', 'd')

so the correct way:

conexao_bd.query("SELECT question, answer FROM ? WHERE id IN ?",[tipo,[a]],function(err, rows){

  if(err) 
     console.log("Erro na query questions: "+err);
  else{
    perguntas.questions.push(rows);
    console.log(JSON.stringify(perguntas));
 }
});


来源:https://stackoverflow.com/questions/20828406/node-mysql-using-array-in-query

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