node-mysql2 icon indicating copy to clipboard operation
node-mysql2 copied to clipboard

A bug in parameters for "IN"

Open tgmazay opened this issue 5 years ago • 6 comments

version 2.2.5

sql : UPDATE table1 SET type = ? WHERE id IN (?) params: ["some_type","1,2,3"]

use connection.execute

type will be changed only for id=1

tgmazay avatar Sep 30 '20 11:09 tgmazay

this is how prepared statements work, in your example you probably want to use .query() or .execute("UPDATE table1 SET type = ? WHERE id IN (?, ?, ?)", ["some_type", 1, 2, 3])

sidorares avatar Sep 30 '20 12:09 sidorares

you can test this in standard command line client using PREPARE sql syntax, see examples at https://dev.mysql.com/doc/refman/8.0/en/sql-prepared-statements.html#prepared-statement-types

sidorares avatar Sep 30 '20 12:09 sidorares

Unfortunately, this issue is still there.

const sql = "SELECT * FROM seller_portfolio_item_images WHERE idseller_portfolio_item IN (?)";
      con.query(sql, [portfolioid_list], function (err, result) {
      console.log(sql);
        if (err) {
          console.log(err);
          var response = errorCodes.internal_server_error;
          callback(null, response);
        }
        else {
          var response = {
            "statusCode": 200,
            "headers": {
              "Content-Type": "application/json"
            },
            "body": JSON.stringify(result),
            "isBase64Encoded": false
          };
          callback(null, response)
        }
      });

If I do the following GET Request, i will get only get records that matched the very first value, in this example, 69.

http://127.0.0.1:3000/sportfolioimages/getbyportfoliolist?portfolioid_list=69,70,71

yohanrw avatar Oct 21 '21 16:10 yohanrw

@yohanrw there is a difference in how .execute() prepared statement parameters are used vs how query() builds sql on the client side. The issue is not unique to this driver, it's general difficulty of using variable length arguments operators/functions with prepared statements. PS need exact match parameter <-> value, and as a result you need variable number of ? parameters in the statement itself.

Good overview of possible solutions: https://stackoverflow.com/questions/178479/preparedstatement-in-clause-alternatives/10240302

sidorares avatar Oct 21 '21 22:10 sidorares