📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (176K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
Setup MySQL database
create database demo;
CREATE TABLE `todos` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
`description` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 AUTO_INCREMENT=1 ;
1. Creating a Node.js Project
$ mkdir node-mysql-crud-tutorial
$ cd node-mysql-crud-tutorial
$ npm init -y
{
"name": "nodejs-mysql-crud-tutorial",
"version": "1.0.0",
"description": "NodeJS + MySQL CRUD Example Tutorial",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [
"NodeJs",
"MySQL",
"CRUD"
],
"author": "Ramesh Fadatare",
"license": "ISC",
"dependencies": {
"mysql": "^2.18.1"
}
}
2. Install MySQL Driver
$npm install mysql --save
var mysql = require('mysql');
3. Performing CRUD Operations
- We create data in the database tables using the INSERT statement.
- We read data from the database tables using the SELECT statement.
- We update data in the database tables using the UPDATE statement.
- We delete data from the database tables using the DELETE statement.
3.1 Creating/Inserting Data
const mysql = require('mysql');
// connection configurations
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'root',
database: 'demo'
});
// connect to database
connection.connect(function (err) {
if (err) throw err
console.log('You are now connected with mysql database...')
});
let params = {
name: "Todo 1",
description: "Todo 1 description"
}
connection.query("INSERT INTO todos SET ? ", params,
function (error, results, fields) {
if (error) throw error;
console.log("Record inserted");
});
$ node .\insert-record.js
You are now connected with mysql database...
Record inserted
3.2 Reading/Selecting data
const mysql = require('mysql');
// connection configurations
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'root',
database: 'demo'
});
// connect to database
connection.connect(function (err) {
if (err) throw err
console.log('You are now connected with mysql database...')
});
// Retrieve and return all todos from the database.
connection.query('select * from todos',
function (error, results, fields) {
if (error) throw error;
console.log(JSON.stringify(results));
});
$ node .\read-record.js
You are now connected with mysql database...
[{"id":2,"name":"Learn Advanced Express.js ","description":"Learn Advanced Express.js with examples"},{"id":3,"name":"Todo 2","description":"Todo 2 description"},{"id":5,"name":"Todo 1","description":"Todo 1 description"}]
3.3 Updating Data
const mysql = require('mysql');
// connection configurations
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'root',
database: 'demo'
});
// connect to database
connection.connect(function (err) {
if (err) throw err
console.log('You are now connected with mysql database...')
});
let params = {
name: "Todo 2",
description: "Todo 2 description"
}
connection.query('UPDATE `todos` SET `name`=?,`description`=? where `id`=?',
[params.name, params.description, 3],
function (error, results, fields) {
if (error) throw error;
console.log("Record updated!");
});
$ node .\update-record.js
You are now connected with mysql database...
Record updated!
3.4 Deleting Data
const mysql = require('mysql');
// connection configurations
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'root',
database: 'demo'
});
// connect to database
connection.connect(function (err) {
if (err) throw err
console.log('You are now connected with mysql database...')
});
let params = {
name: "Todo 1",
description: "Todo 1 description"
}
connection.query(
'DELETE FROM todos where id = ?', [3], (err, result) => {
if (err) throw err;
console.log(result);
}
);
$ node .\delete-record.js
You are now connected with mysql database...
OkPacket {
fieldCount: 0,
affectedRows: 0,
insertId: 0,
serverStatus: 2,
warningCount: 0,
message: '',
protocol41: true,
changedRows: 0 }
Comments
Post a Comment
Leave Comment