How To Store Data In Database Using Node.js

In this article, we will see how to store data in a database using node js. In the previous node js article, I will give you examples of how to connect a MySQL database with Node.js and how to create a MySQL database in Node js. So, now I will give you information about inserting rows into the MySQL database table from node.js or inserting multiple records into MySQL using node.js.

So, let's see, how to save data in a database using node.js or how to insert data into a MySQL table using node js. Before performing this article please make sure to create a database with a connection. So, read the below tutorial for connecting the database.

Example:

var mysql = require('mysql');

var con = mysql.createConnection({
  host: "localhost",
  user: "your_username",
  password: "your_password",
  database: "techsolutionstuff"
});

con.connect(function(err) {
  if (err) throw err;
  console.log("Connected..!!");
  var sql = "INSERT INTO users (name, email) VALUES ('techsolutionstuff', 'test@gmail.com')";
  con.query(sql, function (err, result) {
    if (err) throw err;
    console.log("Record Inserted Successfully!");
  });
});

Run db_record_demo.js file

node db_record_demo.js

The response with console messages like

Connected..!!
Record Inserted Successfully!

 

 

Insert Multiple Records

Insert more than one record, make an array containing the values, and insert a question mark in the SQL, which will be replaced by the value array :

INSERT INTO users (name, email) VALUES ?

Use query() method with SQL statement and data array like below :

connection.query(query, [data]);

Example :

var mysql = require('mysql');

var con = mysql.createConnection({
  host: "localhost",
  user: "your_username",
  password: "your_password",
  database: "techsolutionstuff"
});

con.connect(function(err) {
  if (err) throw err;
  console.log("Connected..!");
  var sql = "INSERT INTO users (name, email) VALUES ?";
  var values = [
    ['techsolutionstuff', 'test@gmail.com'],
    ['dell', 'dell@test.com'],
    ['laravel', 'laravel@test.com']
  ];
  con.query(sql, [values], function (err, result) {
    if (err) throw err;
    console.log("Number of records inserted: " + result.affectedRows);
  });
});

Run db_record_demo.js file

node db_record_demo.js

The response with console messages like :

Connected..!!
Number of records inserted: 3

 


You might also like:

techsolutionstuff

Techsolutionstuff | The Complete Guide

I'm a software engineer and the founder of techsolutionstuff.com. Hailing from India, I craft articles, tutorials, tricks, and tips to aid developers. Explore Laravel, PHP, MySQL, jQuery, Bootstrap, Node.js, Vue.js, and AngularJS in our tech stack.

RECOMMENDED POSTS

FEATURE POSTS