How to run multiple statements in one query with node-mysql?

Sometimes, we want to run multiple statements in one query with node-mysql.

In this article, we’ll look at how to run multiple statements in one query with node-mysql.

How to run multiple statements in one query with node-mysql?

To run multiple statements in one query with node-mysql, we can call connection.query with all our SQL statements.

For instance, we write

connection.query('SELECT ?; SELECT ?', [1, 2], (err, results) => {
  if (err) {
    throw err;
  }

  const [r1, r2] = results
  console.log(r1);
  console.log(r2);
});

to call query with 2 SELECT statements separated by a semicolon.

And then we pass in an array the values for the ? in the SQL code.

Next, we pass in a callback that has the SELECT query results stored in the results parameter.

As a result, r1 is [{1: 1}] and r2 is [{2: 2}].

Conclusion

To run multiple statements in one query with node-mysql, we can call connection.query with all our SQL statements.