Home >>Nodejs Tutorial >Node.js MySQL Insert Records

Node.js MySQL Insert Records

Node.js MySQL Insert Records

INSERT INTO statement is used for record insertion in MySQL.

Example

Insert Single Record:

Insert records into a table called "users".

Create a js file in DBexample folder called "insert.js" and put the following data into it:


var db = require('db');  
var con = db.createConnection({  
host: "localhost",  
user: "root",  
password: "",  
database: "phptpoint"  
});  
con.connect(function(err) {  
if (err) throw err;  
console.log("Connected!");  
var sql = "INSERT INTO users (id, name, email) VALUES ('1', 'Rexx', 'Rexx@gmail.com')";  
con.query(sql, function (err, result) 
{  
if (err) throw err;  
console.log("1 record inserted");  
});  

Now open terminal command and execute the following command:

Node insert.js

Check the record you have inserted using SELECT query:

SELECT * FROM users;

Insert Multiple Records

Create a js file in DBexample folder called "insertall.js" and put the following data into it:


var db = require('db');  
var con = db.createConnection({  
host: "localhost",  
user: "root",  
password: "",  
database: "phptpoint"  
});  
con.connect(function(err) {  
if (err) throw err;  
console.log("Connected!");  
var sql = "INSERT INTO employees (id, name, email) VALUES ?";  
var values = [  
['2', 'Anshika', 'anshika@gmail.com'],  
['3', 'Sumit', 'sumit@gmail.com'],  
['4', 'Archana', 'archana@gmail.com']  
];  
con.query(sql, [values], function (err, result) {  
if (err) throw err;  
console.log("Number of records inserted: " + result.affectedRows);  
});  
});  

Now open terminal command and execute the following command:

Node insertall.js

The Result Object

When the insert() method is executed a result object will be returned. The result object contains insert information


No Sidebar ads