Home » Node.js

Insert data in MYSQL table by using Node.js

In this article, we are going to learn how to insert a record in MYSQL table using Node.js server?
Submitted by Manu Jemini, on November 21, 2017

Prerequisite:

Now, in this article, the very first thing we are going to do is to prepare a server file of node.js where we require the MySQL module to work with MySQL and after that, we prepare a connection by using mysql.createConnection() method of MySQL module.

There are certain things that we have to define inside our create connection methods like host, user, password, and database name.

Now that we are all set to go with our connection, all we need to create a SQL query to insert data basically an insert query and after that we can use .query() method to execute query statement with a callback function in which we can throw error if any and print the message where we can show the number of affected rows.

Note: For inserting the record in a table we must have the name of the table.

Database details:

  • Hostname: localhost
  • Port number: 3306
  • Username: root
  • Password: 123
  • Database: demo
  • Table name: clients

Server File

//step-1
var mysql = require('mysql');
//step-2
var con = mysql.createConnection({
  host: "localhost",
  user: "root",
  password: "123",
  database: "demo"
});

//step-3
con.connect(function(err) {
  if (err) throw err;
  console.log("Connected!");
  //step-4
  var sql = "INSERT INTO Clients (id, name, address) VALUES ?";
  //step-5
  var values = [
    ['1', 'Aman', 'Delhi'],
    ['2', 'Rahul', 'Banglore'],
    ['3', 'Shivam', 'Mumbai'],
  ];
  //step-6
  con.query(sql, [values], function (err, result) {
    if (err) throw err;
    console.log("Number of records inserted: " + result.affectedRows);
  });
});

Discussing steps that we have followed in our server file:

  • Require MySQL module.
  • Create Connection variable using mysql.createConnection() method.
  • Connect by using con.connect() method.
  • Creating SQL query.
  • Insert values.
  • Execute query by using .query() method.
Node.js - Insert record in MySQL table

Insert record in MySQL table using Node.js

If you have any query do comment.



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.