In this article we will learn about how we can perform CRUD (Create , Read , Update , Delete) operations in MySQL using Node.js
I will be referring to Node.js as node from here onwards in this article.
npm install mysql
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'my_db'
});
//Here is the Query for create(i.e. Insertion) is stored in the variable "insert"
var insert = 'INSERT INTO details(name,lastname,age,mobile) VALUE(?,?,?,?)';
//Inserting a Record in TABLE details
connection.query(insert,['ricky','sharma','25','9876543210'], function(Error,Record){
if(Error){
console.log("An Error occured : " + Error);
}
else{
console.log('New Details Added Successfully');
}
});
//Here is the Query for Read(i.e. Retrieve) operation which is stored in the variable read.
var read = 'SELECT * FROM details';
//Retrieving all the Records from the table "details"
connection.query(read,function(Error,Record){
if(Error){
console.log("An Error occured : " + Error);
}
else{
console.log('Recods : ' + JSON.stringify(Record));
}
});
//Here is the Query for Update operation which is stored in the variable update.
var update = 'UPDATE details SET age = ? WHERE name=?';
//Updating the age of records where name = "Ricky"
connection.query(update,[30,'Ricky'],function(Error,Record){
if(Error){
console.log("An Error occured : " + Error);
}
else{
console.log('Updated Successfully');
}
});
//the Query for delete operation is stored in the variable delete.
var r_delete = 'DELETE FROM details WHERE name=?';
//Deleting the record where name = "Ricky"
connection.query(r_delete,['Ricky'],function(Error,Record){
if(Error){
console.log("An Error occured : " + Error);
}
else{
console.log('Deleted Successfully');
}
});