Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node-mysql single value for multiple query parameters

Currently, in node.js, if I want to search for a string in multiple columns in a MySQL table I have to do like this:

mysqlConnection.query(
    "SELECT * FROM my_table WHERE column_a LIKE ? OR column_b LIKE ? OR column_c LIKE ?",
    [searchString, searchString, searchString],
    callback
);

I want to be able to do it like this:

mysqlConnection.query(
    "SELECT * FROM my_table WHERE column_a LIKE ? OR column_b LIKE ? OR column_c LIKE ?", 
    searchString, callback
);

Or maybe even with named parameters:

mysqlConnection.query(
    "SELECT * FROM my_table WHERE column_a LIKE :searchString OR column_b LIKE :searchString OR column_c LIKE :searchString",
    {searchString: "needle"},
    callback
);

Is there a way I can do it?

like image 448
starleaf1 Avatar asked Nov 18 '22 23:11

starleaf1


1 Answers

you can enable named parameter when creating your db pool connection.

const connection = mysql.createPool({
  ...yourConfig,
  namedPlaceholders: true,
});

edit: As @robertklep explained it only works on mysql2 npm package

like image 106
Rafo Avatar answered Dec 11 '22 06:12

Rafo