insert multiple Row in SQL database with NodeJS

To insert multiple rows into an SQL database using Node.js, you can follow these steps:

  1. Import the necessary modules:
  2. First, you need to import the required modules to work with the database. In this case, we will use the mysql module for connecting and interacting with the MySQL database.

  3. Create a database connection:

  4. Next, you need to establish a connection to your MySQL database. You can use the mysql.createConnection() method to create a connection object by providing the necessary connection details like host, user, password, and database name.

  5. Define the SQL query:

  6. After establishing the connection, you need to define the SQL query that will insert multiple rows into the database. The query should be constructed using the INSERT INTO statement, specifying the table name and the column names.

  7. Prepare the data for insertion:

  8. Before executing the query, you need to prepare the data that will be inserted into the database. This can be done by creating an array of objects, where each object represents a row to be inserted. Each object should contain key-value pairs representing the column names and their corresponding values.

  9. Execute the query:

  10. Once the data is prepared, you can execute the query using the connection.query() method. Pass the SQL query and the data array as parameters to this method.

  11. Handle the result:

  12. Finally, you can handle the result of the query execution. You can use a callback function to handle any errors that may occur during the execution. If the query is successful, you can perform any further operations or log a success message.

Here is an example of how these steps can be implemented in Node.js:

const mysql = require('mysql');

const connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: 'password',
  database: 'mydatabase',
});

const rows = [
  { name: 'John', age: 25 },
  { name: 'Jane', age: 30 },
  { name: 'Bob', age: 35 },
];

const query = 'INSERT INTO users (name, age) VALUES ?';

connection.query(query, [rows.map(row => [row.name, row.age])], (error, result) => {
  if (error) {
    console.error('Error:', error);
  } else {
    console.log('Rows inserted:', result.affectedRows);
  }
});

connection.end();

This example assumes you have a MySQL database named mydatabase with a table named users that has name and age columns. It inserts multiple rows into the users table using the provided data array.