How to bulk insert in MySQL using Node.js?

Sometimes, we want to bulk insert in MySQL using Node.js.

In this article, we’ll look at how to bulk insert in MySQL using Node.js.

How to bulk insert in MySQL using Node.js?

To bulk insert in MySQL using Node.js, we can use the connection’s query method.

For instance, we write

const mysql = require('mysql');
const conn = mysql.createConnection({
  //...
});

const sql = "INSERT INTO Test (name, email, n) VALUES ?";
const values = [
  ['demian', '[email protected]', 1],
  ['john', '[email protected]', 2],
  ['mark', '[email protected]', 3],
  ['pete', '[email protected]', 4]
];
conn.query(sql, [values], (err) => {
  if (err) throw err;
  conn.end();
});

to create the DB connection with mysql.createConnection.

Then we call conn.query with the sql and the values in a nested array to insert them all into the SQL.

The ? in the sql will be interpolated with the values to insert.

Then we call conn.end to end the DB connection once the data are inserted.

Conclusion

To bulk insert in MySQL using Node.js, we can use the connection’s query method.