0
0

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.

jsで文字列に変数埋め込みをする場合、mysqlライブラリのquery()を用いた際の注意

0
Last updated at Posted at 2019-10-22

環境

nodeJS

プログラム

他の処理で得られた値を使ってsql作成する場合に以下のようなプログラムを作っていた

server.js
connection.query(`select ${column_name} from ${table_name} where ${column_name}みたいな`, function (err, rows, fields) {
  if (err) { console.log('err: ' + err); } 
});

しかし、上記の場合エラーとなる。
バッククォートを用いた文字列を直接第一引数に入れてしまうのが問題。

以下のように、いったん変数に入れたら改善された

server.js
let sql = `select ${column_name} from ${table_name} where ${column_name}みたいな`

connection.query(sql, function (err, rows, fields) {
  if (err) { console.log('err: ' + err); } 
});

結果

ふぅ〜!呼び出せた!

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?