The prepared statements document for mysql2 shows positional parameters. While there is some discussion about named parameters, as far as I can tell, they're not documented. If they're supported, how can named parameters be used?
For example, how would the following be converted to using named parameters?
const config = require('config'); // for DB connection info
const mysql = require('mysql2/promise');
const connection = await mysql.createConnection({
...config.get('db.conn'),
// (or however connection information is retrieved locally)
})
let sql = "SELECT ? AS a, ? AS b, ? + ? AS ab",
values = [2, 3, 2, 3];
// note values[2:3] must equal values[0:1], otherwise results will be incorrect
let [result, columns] = await connection.execute(sql, values);
(Note that DB connection information is left out of the sample and is represented by the use of the config package. Before being run locally, the sample must be completed by providing connection information in whatever manner is preferred.)
mysql2 has some support for named parameters (sometimes called "named placeholders" in mysql2) via the named-placeholders package. The feature is disabled by default, and so must be enabled with the
namedPlaceholders
option when the connection or pool is created, or when the query is executed.Named placeholders use a similar syntax to that in PHP: a colon followed by the name. Unlike PHP, the name is allowed to be a number as well as an identifier. Also unlike PHP, the name used in the values object must not be preceded by a colon, else the value won't be found.
Named placeholders are supported in the
query
andexecute
methods, andConnection.format
ifnamedPlaceholders
is true for the connection. They aren't supported byprepare
,mysql.format
orPool.format
.Connection.format
also supports named placeholders for identifiers; the name must be preceded by two colons, rather than one. Unlike with positional parameters, all parameters must be passed toConnection.format
if positional parameters are being processed; any unspecified parameters, whether named or positional, becomeNULL
(for values) or`undefined`
(for identifiers).