Categories
JavaScript Answers

How to bulk insert in MySQL using Node.js?

Spread the love

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', 'jane@gmail.com', 1],
  ['john', 'mary@gmail.com', 2],
  ['mark', 'alex@gmail.com', 3],
  ['pete', 'pete@gmail.com', 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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *