1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

mysql2/promiseでnamedPlaceholdersオプションを有効にする

Last updated at Posted at 2018-08-26

createConnection()またはcreatePool()の引数に渡すオブジェクトの中にnamedPlaceholders = trueを記述する。


const mysql2 = require("mysql2");

(async () => {
    const conn = await mysql2.createPool({
        host: 'localhost',
        user: 'root',
        database: 'mysql',
        namedPlaceholders: true, // <- ここ
    }).promise();

    const query = "SELECT User FROM user WHERE Host = :param"
    const param = "localhost";
    try {
        const [row, fields] = await conn.query(query, { param });
        console.log(row);
    } catch (e) {
        console.log(e);
    }
    return;
})();

promise化しない場合は上の方法でも公式リファレンス通りでもどちらでもOKです。

また、プレースホルダを有効にすると???は使えなくなります。
ですが???をプレースホルダに置き換えて上げれば2重配列やINSERT文のSET句は同様に展開されるので問題ないはずです。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?