简体   繁体   中英

Multiple wildcards via prepared statements for node.js mysql query

I have a JSON like this:

{"name":[{"tag":"Peter"}]}

And I'm dynamically building a prepared statement with multiple wildcards like this:

var sqlVar;
sqlVar += existParams.map(field => {
    if (field === 'name') {
        function getValues(item, index) {
          var getVal = [item.tag];
          return `${field} LIKE ?`;
        }
        return '('+name.map(getValues).join(' OR ')+')';
    } else {
        return `(${field} = ?)`
    }
}).join(" AND ");

var sql = "SELECT * FROM names "+sqlVar+"";

connection.query(sql,
    ... 
    function getValues(item, index) {
      var getVal = [item.tag];
      return '%' + getVal + '%';
    }
    return name.map(getValues);

    //Further attempts
    //var getResult = name.map(getValues);
    //return getResult.split(",");
    //return name.map(getValues).join(', ');        

    , function(err, rows) {
    ...
});

If I have one value it works just fine. In console.log (SQL) I can see:

SELECT * FROM names WHERE (name LIKE ?)

BUT... if I have multiple values like:

{"name":[{"tag":"Peter"},{"tag":"Jack"}]}

I'm getting an SQL Error:

sql: 'SELECT * FROM names WHERE (name LIKE \'%Peter%\', \'%Jack%\' OR name LIKE ?) }

... So the second value is not going to the second position.

... but the result should be:

sql: 'SELECT * FROM names WHERE (name LIKE \'%Jack%\' OR name LIKE \'%Peter%\') }

... so in the console.log(sql):

SELECT * FROM names WHERE (name LIKE ? OR name LIKE ?)

What am I missing and how can I get the second value to the second LIKE and so on?!

Here is a similar example but with only one value: nodejs throws error with mysql like query via prepared statements

The only reason here for the resulting statement to be 'SELECT * FROM names WHERE (name LIKE \\'%Peter%\\', \\'%Jack%\\' OR name LIKE ?)

is that you have passed a nested array with value [['%Peter%', '%Jack%']] instead of a flat one.

Using the given object say,

const source = {"name":[{"tag":"Peter"}, {"tag":"Jack"}]}

Then the query values for the prepared statement should be

const queryValues = source.name.map(({tag}) => `%${tag}%`);
// [ '%Peter%', '%Jack%' ]

connect.query(sql, queryValues, (err, rows) => {
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM