Home >Database >Mysql Tutorial >How to Perform Bulk Inserts in MySQL using Node.js?

How to Perform Bulk Inserts in MySQL using Node.js?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-13 06:22:09725browse

How to Perform Bulk Inserts in MySQL using Node.js?

Bulk Insertion in MySQL Using Node.js

Performing bulk insertions in MySQL can be achieved utilizing the node-mysql library. To achieve this, nested arrays can be employed.

Syntax:

[ ['a', 'b'], ['c', 'd'] ]

Example:

// Import the node-mysql module
var mysql = require('mysql');

// Establish a connection to the database
var conn = mysql.createConnection({
    ...
});

// Define the SQL query
var sql = "INSERT INTO Test (name, email, n) VALUES ?";

// Construct the array of values
var values = [
    ['demian', '[email protected]', 1],
    ['john', '[email protected]', 2],
    ['mark', '[email protected]', 3],
    ['pete', '[email protected]', 4]
];

// Execute the bulk insert query
conn.query(sql, [values], function(err) {
    if (err) throw err;
    conn.end();
});

Note: The values array is a two-dimensional array of arrays. This enables the insertion of multiple rows simultaneously.

Additional Notes:

  • Alternatively, the node-mysql-plus package can be used for bulk insertions.
  • Avoid using ; when executing bulk inserts.

The above is the detailed content of How to Perform Bulk Inserts in MySQL using Node.js?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn