DEV Community

Techsolutionstuff
Techsolutionstuff

Posted on • Originally published at techsolutionstuff.com

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!");
  });
});
Enter fullscreen mode Exit fullscreen mode

Run db_record_demo.js file

node db_record_demo.js
Enter fullscreen mode Exit fullscreen mode

The response with console messages like

Connected..!!
Record Inserted Successfully!
Enter fullscreen mode Exit fullscreen mode

Read More: Insert Multiple Records Using Node.js on Original Post

Latest comments (0)