Home >Database >Mysql Tutorial >How Can I Perform Bulk Inserts into MySQL Using Node.js?

How Can I Perform Bulk Inserts into MySQL Using Node.js?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-25 10:43:09227browse

How Can I Perform Bulk Inserts into MySQL Using Node.js?

Bulk Inserting Data into MySQL using Node.js with MySQL

If you're utilizing node-mysql, there are various methods to execute bulk inserts into MySQL. One approach involves employing nested arrays to group values for insertion:

Nested Arrays Implementation

Within the SQL query, specify the VALUES clause as a question mark (?) to indicate the placeholder for values to be inserted.

INSERT INTO Test (name, email, n) VALUES ?

Prepare the data as a nested array, with each sub-array representing a row to be inserted:

var values = [
    ['demian', '[email protected]', 1],
    ['john', '[email protected]', 2],
    ['mark', '[email protected]', 3],
    ['pete', '[email protected]', 4]
];

Next, pass the array of arrays to the query method as an argument:

conn.query(sql, [values], function(err) {
    if (err) throw err;
    conn.end();
});

In this example, values is a nested array wrapped in another array.

Alternative Bulk Insertion Package

There exists another Node.js package specifically designed for bulk insertion into MySQL:

  • node-mysql-bulk-insert:

This package offers specialized functionality for efficiently inserting large amounts of data into MySQL.

The above is the detailed content of How Can I Perform Bulk Inserts into 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