Inserting Records into Table using Node

Node.jsServer Side ProgrammingProgramming

In this article, we will see how we can insert data into a table using NodeJS. Read the complete article to understand how we can save data into the database table.

Before proceeding, please check the following steps are already executed −

  • mkdir mysql-test

  • cd mysql-test

  • npm init -y

  • npm install mysql

The above steps are for installing the Node - mysql dependecy in the project folder.

Insert a Record into the Students Table

  • For adding the new records into the MySQL table, firstly create an app.js file

  • Now copy-paste the below snippet in the file

  • Run the code using the following command

>> node app.js

Example

// Checking the MySQL dependency in NPM
var mysql = require('mysql');

// Creating a mysql connection
var con = mysql.createConnection({
   host: "localhost",
   user: "yourusername",
   password: "yourpassword",
   database: "mydb"
});

con.connect(function(err) {
   if (err) throw err;
   console.log("DB Connected!");
   var sql = "INSERT INTO students (name, address) VALUES ('John', 'Delhi')";
   con.query(sql, function (err, result) {
      if (err) throw err;
      console.log("Successfully inserted 1 record.");
   });
});

Output

After Inserting the record, we will get the following output −

Successfully inserted 1 record.

Insert Multiple Records into the Students Table

  • For adding new records into the MySQL table, firstly create an app.js file

  • Now copy-paste the below snippet in the file

  • Run the code using the following command

>> node app.js

Example

// Checking the MySQL dependency in NPM
var mysql = require('mysql');

// Creating a mysql connection
var con = mysql.createConnection({
   host: "localhost",
   user: "yourusername",
   password: "yourpassword",
   database: "mydb"
});

con.connect(function(err) {
   if (err) throw err;
   console.log("DB Connected!");
   var sql = "INSERT INTO students (name, address) VALUES ('Pete', 'Mumbai'), ('Amy', 'Hyderabad'), ('Hannah', 'Mumbai'), ('Mike', 'Delhi')";
   con.query(sql, function (err, result) {
      if (err) throw err;
      console.log("Successfully inserted multiple records into the table.");
   });
});

Output

The above program will give the following output after insertion −

Successfully inserted multiple records into the table.
raja
Published on 27-Apr-2021 11:19:53
Advertisements