Node js MySQL Insert

INSERT command is used to insert data in the database. For this first we make a connection to the database, then write an insert query to insert records in the table.

Syntax

INSERT INTO Tablename (field1, field2, filed3) VALUES ?; 

Example

In this given example, we have inserted single row data in 'department' table.

var mysql = require('mysql');
var con = mysql.createConnection({
   host: "hostname",
   user: "username",
   password: "password",
   database: "database"
});

con.connect(function(error){
    if(error) {
        console.log('Error establishing connection to db');
        return;
    }
    console.log('Connection Established'); 
    var department = {id: '1', name: 'Software', emp_length: '22'};
    var insertdata = "INSERT INTO department SET ?";
    con.query(insertdata, department, function (error) {  
    if(error) { 
        console.log('Error in inserting records in table');
    }  
    console.log("Data inserted");  
    });  
});

Open cmd and run the above file as -

node insertdata.js

Insert multiple records into MySQL table using Node js

We can also insert multiple rows data in a single query, like in this given example, we have inserted multiple records in 'department' table.

var mysql = require('mysql');
var con = mysql.createConnection({
   host: "hostname",
   user: "username",
   password: "password",
   database: "database"
});

con.connect(function(error){
    if(error) {
        console.log('Error establishing connection to db');
        return;
    }
    console.log('Connection Established'); 
    var data = [
                  [2, 'Accounting',5],
                  [3, 'Hardware',10]
                 ];
    var insertdata = "INSERT INTO department(id, name, emp_length) VALUES ?";
    con.query(insertdata, [data], function (error) {  
    if(error) { 
        throw(error);
        //console.log('Error in inserting records in table');
    }  
    console.log("Data inserted");  
    });  
});

Open cmd and run the above file as -

nodejs mysql insert data


Read more articles


General Knowledge



Learn Popular Language