guagay_wk
guagay_wk

Reputation: 28030

How to conveniently insert a MySQL query as argument into Javascript function?

I have this MySQL query which works fine in Node.js.

connection.query(
    'SELECT reading.device_id,' +
    'reading.temperature,' +
    'reading.humidity,' +
    'reading.light,' +
    'reading.time_taken ' +
    'FROM sensors.reading reading',
    function (err, results, fields) {
        console.log(results);
        console.log(fields);
    }

However, it is inconveniently adding those + signs at the end of each line of the query.

Can I do something like this in javascript similar to what is done in python?

connection.query(
    """SELECT reading.device_id,
        reading.temperature,
        reading.humidity,
        reading.light,
        reading.time_taken
    FROM sensors.reading reading""",
    function (err, results, fields) {
        console.log(results);
        console.log(fields);
    }

Of course, this won't work in javascript. But I am wondering how can I avoid adding those + signs at the end of each line in the query.

Upvotes: 2

Views: 35

Answers (1)

KeyNone
KeyNone

Reputation: 9150

You can use the backslash:

connection.query(
  "SELECT reading.device_id,\
     reading.temperature,\
     reading.humidity,\
     reading.light,\
     reading.time_taken \
   FROM sensors.reading reading",
  function (err, results, fields) {
    console.log(results);
    console.log(fields);
  }
)

Be aware that this is quite undefined, as this is not part of the ECMA spec. It can break minifiers and may not be supported at all.

Upvotes: 1

Related Questions