Incorrect arguments to mysqld_stmt_execute, params matching query

140 Views Asked by At

I am trying to search through rows in a mysql table with mysql2 using LIKE, but i am getting an error in the console about incorrect arguments. The params for the prepared statement are matching the needs of the query string.

Code:

import mysql from "mysql2";

export const searchMovies = (phrase: string, limit: number): Promise<Movie[]> => {
    return new Promise((resolve, reject) => {
        const pattern = `%${phrase.replace("!", "!!").replace("%", "!%").replace("_", "!_")}%`;
        const sql = "SELECT * FROM movies WHERE `Name` LIKE ? LIMIT ?";
        const params = [pattern, limit];
        db.execute(sql, params, (err, rows: RowDataPacket[]) => {
            if (err) reject(err);
            if (rows == undefined) return [];
            resolve(rows.map(x => ({
                id: x.ID,
                name: x.Name,
                language: x.Language,
                year: x.Year
            })));
        });
    });
};

Console error:

/home/node/app/node_modules/mysql2/lib/packets/packet.js:728
    const err = new Error(message);       
                ^

Error: Incorrect arguments to mysqld_stmt_execute
    at Packet.asError (/home/node/app/node_modules/mysql2/lib/packets/packet.js:728:17)
    at Execute.execute (/home/node/app/node_modules/mysql2/lib/commands/command.js:29:26)
    at Connection.handlePacket (/home/node/app/node_modules/mysql2/lib/connection.js:478:34)
    at PacketParser.onPacket (/home/node/app/node_modules/mysql2/lib/connection.js:97:12)
    at PacketParser.executeStart (/home/node/app/node_modules/mysql2/lib/packet_parser.js:75:16)
    at Socket.<anonymous> (/home/node/app/node_modules/mysql2/lib/connection.js:104:25)
    at Socket.emit (node:events:514:28)   
    at addChunk (node:internal/streams/readable:376:12)
    at readableAddChunk (node:internal/streams/readable:349:9)
    at Readable.push (node:internal/streams/readable:286:10) {
  code: 'ER_WRONG_ARGUMENTS',
  errno: 1210,
  sqlState: 'HY000',
  sqlMessage: 'Incorrect arguments to mysqld_stmt_execute',
  sql: 'SELECT * FROM movies WHERE `Name` LIKE ? LIMIT ?'
}
1

There are 1 best solutions below

1
On
import mysql from "mysql2";

export const searchMovies = (phrase: string, limit: number): Promise < Movie[] > => {
  return new Promise((resolve, reject) => {
    const pattern = `%${phrase.replace("!", "!!").replace("%", "!%").replace("_", "!_")}%`;
    const sql = "SELECT * FROM movies WHERE `Name` LIKE ? LIMIT ?";
    const params = [pattern, limit];
    db.execute(sql, params, (err, rows: RowDataPacket[]) => {
      if (err) reject(err);
      if (rows == undefined) return [];
      resolve(rows.map(x => ({
        id: x.ID,
        name: x.Name,
        language: x.Language,
        year: x.Year
      })));
    });
  });
};