Full Trust European Hosting

BLOG about Full Trust Hosting and Its Technology - Dedicated to European Windows Hosting Customer

Node.js Hosting - HostForLIFE :: Getting Started With Node.js And MYSQL (CRUD Operation)

clock February 11, 2022 08:00 by author Peter

In this article, we will develop APIs in Node JS for back-end operations and implement a CRUD operation in it.

Prerequisites

    Visual studio code
    Node version installed in the system
    Postman

Create a new blank folder on your desired location. Now, open cmd and go to the newly created location and write " code . " to open folder in visual studio code.

    In the cmd write below code to initiate the node app by default configurations.

npm init //press enter until you see package.json in the folder structure

At this point of time, a blank package.json will be added into the project.

    We have created basic node app now let's import our required dependencies and npm packages. We will be using express, mysql2, and,nodemon npm packages

npm i express mysql2 nodemon

Database: I have used mysql workbench (you can use any database of your choice)
I have created a simple database called employeedb through MySQL workbench and a table called employee.
Columns in the table and stored procedure for insert and update employee

  • EmpId - Int
  • Name - Varchar(100)
  • EmpCode - Varchar(50)
  • Salary - Decimal
CREATE TABLE `employee` (
  `EmpId` int NOT NULL AUTO_INCREMENT,
  `Name` varchar(100) NOT NULL,
  `EmpCode` varchar(40) NOT NULL,
  `Salary` int DEFAULT NULL,
  PRIMARY KEY (`EmpId`)
) ENGINE=InnoDB AUTO_INCREMENT=49 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;

Stored procedure for insert and update employee - EmployeeAddOrEdit
CREATE DEFINER=`root`@`localhost` PROCEDURE `EmployeeAddOrEdit`(
    IN _EmpId INT,
    IN _Name varchar(100),
    IN _EmpCode varchar(40),
    IN _Salary INT)
BEGIN
IF _EmpId= 0  THEN
        INSERT INTO employee (Name, EmpCode,Salary)
        Values (_Name,_EmpCode,_Salary);

        SET _EmpId = LAST_INSERT_ID();
    ELSE
        Update employee
        SET
        Name = _Name,
        EmpCode=_EmpCode,
        Salary = _Salary
        Where EmpId=_EmpId;
    END IF;

Let's create config.js file to store database credentials. Create new file called "config.js" and write below code.
const config = {
    app: {
        port: 3000
    },
    db: {
        host: 'localhost',
        user: 'root',
        password: 'softweb#567',
        database: 'employeedb',
        multipleStatements: true
    }
};

Let's import config.js file in the index.js file, create a connection string and connect to the database as well as we will listen to the 3000 port through express server.
const mysql = require('mysql2');
const express = require('express');
var app = express();

app.use(express.json());
const config = require('./config');
const { db: { host, user, password, database, multipleStatements }, app: { port } } = config;

var connection = mysql.createConnection({
    host: host,
    user: user,
    password: password,
    database: database,
    multipleStatements: multipleStatements
});

connection.connect((err) => {
    if (!err)
        console.log('Database connected successfully');
    else
        console.log('Database connection failed' + JSON.stringify(err, undefined, 2));
});

app.listen(port, () => console.log('Express server started at port no : ' + port));

To check whether our code is working or not run the node application and see the logs.
node index.js

Database has been connected successfully now !! :)

Let's develop node APIs now.

1. Get Employees: In order to make query call to database we will use query method of conenction object and in the callback function of the query function we log the response if there is no error.

We have to pass specific employee id in order to fetch particular employee record. Hence, we have passed it in the api by ":id".
//get all employees
app.get('/employees', (req, res) => {
    connection.query('select * from employee', (err, rows, fields) => {
        if (!err)
            res.send(rows);
        else
            console.log(err);
    })
});


//get employee by id
app.get('/employee/:id', (req, res) => {
    connection.query('select * from employee where empid=?', [req.params.id], (err, rows, fields) => {
        if (!err)
            res.send(rows);
        else
            console.log(err);
    })
});


If any error in the calling API then we have logged it in the console otherwise we could be able to see the response of the postman. (We will be using postman for the calling node APIs)


2. Delete the employee record
//delete employee
app.delete('/employee/:id', (req, res) => {
    connection.query('delete from employee where empid=?', [req.params.id], (err, rows, fields) => {
        if (!err)
            res.send('Record deleted successfully.')
        else
            res.send(err);
    })
});

Call delete API in postman
http://localhost:3000/employee/1 //Pass employee id with delete type of the API

3. Insert employee record: We have to first read the employee object that we have sent via the API body. Furthermore, we will pass the required parameter in the stored procedure by SET and CALL the stored procedure.

Note: We have to pass EmpId as 0 to notify that our intention is to insert the record. (Refer to our stored procedure code above)
//post employee
app.post('/employee/', (req, res) => {
    //console.log(req.body.body);
    var emp = req.body;
    console.log(emp);
    var sql = `set @EmpId=?;set @Name=?;set @EmpCode=?;set @Salary=?;
               CALL EmployeeAddOrEdit(@EmpId,@Name,@EmpCode,@Salary)`
    connection.query(sql, [emp.EmpId, emp.Name, emp.EmpCode, emp.Salary], (err, rows, fields) => {
        if (!err) {
            const emp = rows.filter(function (elem) {
                return elem.constructor == Array;
            });
            res.send('Inserted Id : ' + emp[0][0].EmpId);
        }
        else
            res.send(err);
    })
});

 

4. Update employee record
//update employee
app.put('/employee/', (req, res) => {
    var emp = req.body;
    var sql = `set @EmpId=?;set @Name=?;set @EmpCode=?;set @Salary=?;
               CALL EmployeeAddOrEdit(@EmpId,@Name,@EmpCode,@Salary)`
    connection.query(sql, [emp.EmpId, emp.Name, emp.EmpCode, emp.Salary], (err, rows, fields) => {
        if (!err) {
            res.send('Updated successfully');
        }
        else
            res.send(err);
    })
});


Similar to post API we will pass the mode of the employee but this time with a specific employee id so that it indicates that we are updating a record.

Therefore, our request would look like below with the EmpId


This was just a jumpstart in node js to understand database connectivity and basic crud operations. Validations, API filter, and more such features we will look into it in the future.



European Visual Studio 2022 Hosting - HostForLIFE :: Hidden Features Of Visual Studio That Developer Should Know

clock February 8, 2022 06:46 by author Peter

Most of the .NET developers are using Visual Studio IDE for their development. The Visual Studio IDE has a lot of cool hidden features. Most of the developers are not aware of these features. In this article, we are going to explore hidden features available in Visual Studio.

1) Track active document in the solution
While working on the large solution (which has several numbers of projects), tracking of current opening file in the solution is difficult. If we want to track, then we have to scroll the entire solution explorer to find out the working files or search for a specific file inside solution explorer. It is too difficult and also time-consuming process. But Visual Studio has tracking feature which helps us to understand where we are in the solution/projects.

Visual Studio can automatically highlight the active/working files in the solution by clicking on the "Sync with Active Document" option in the top bar of the solution explorer.

Disadvantage of the above approach is every time we have to manually click this option to track files. Then how to do it automatically without manual action? Yes!!!! Visual Studio has that feature also. Cool.

Follow the below steps to enable the auto tracking feature.

Step 1
Go Tools -> Options

Step 2
Select Projects and Solutions -> General on the left pane

Step 3
Select the option "Track Active Item in Solution Explorer"

This will track your current working files automatically in the solution explorer.

2) Copy multiple items to the clipboard
Mostly if we want to copy multiple lines of code from different places and paste them in a single place or when we needed, then mostly we would copy and paste one by one. It is always affecting our productivity. Then, how to copy multiple code block, and paste them as and when needed? This is another hidden feature of Visual Studio. This built-in feature is known as “Clipboard Ring”. Just cut/copy the code blocks which are stored in a memory and you can use them later by pasting.

How it works?
    Copy (ctrl + c) / Cut (ctrl + x) the number of code blocks.
    Press ctrl+shit+v Option. A small pop-up window is displayed with all copied items. You can choose which one wants to paste.
    Use the same key set to paste the copied items. The clipboard store only the last 15 copied items in the memory.

3) Separate and Maintaining the pinned tabs in Visual Studio
Most of the times we have pinned the frequently used files. Even if pinned the files, those files are aligned with other opened files in a single row. So, it is difficult to maintain/track the pinned files with other files. Pinned Tabs are very useful features in Visual Studio where we can maintain the pinned files in a separate row and refer them quickly.

Go to Tools -> Options -> Environment -> Tabs and Windows and checked the  "Show pinned tabs in separate row" option.

4) Use "Run To Cursor" and save time while debugging
It is another cool hidden feature which can improve productivity while debugging. If we want to stop the debugger in a particular line then most of us add the breakpoint and run the application. So, the debugger will stop on the targeting line. Is it possible to reduce the work? Yes. We can.

"Run to Cursor" is just like another breakpoint, but in this case, we don’t need to start the Visual Studio debugger manually and the breakpoints are cleared when it’s hit. When you select the "Run to Cursor" option, visual studio starts the debugger automatically and stopped on the selected line.

Right click on the line where you want to stop the debugger, select the "Run to Cursor" option from the context menu. The Visual Studio starts the application and it will stop on the line you had selected. From here we can continue the debugging. Shortcut for this option is "ctrl + F10".

5) Open the application in the multiple Browsers
While working on the web application (mostly front-end), we want to test the application in different browsers. When we run the application, it will open in the default browser. Most of the time we manually copied the URL and opened it in another browser. Do you think, is this improve our productivity? No Definitely Not. Visual Studio has the option to run the application in different browsers with just a single click.

Follow the below steps to open the application in multiple browsers.

Step 1

Click on run dropdown -> Web Browser -> Click "Select Web Browsers... " option.

Step 2
The Browser option window will be displayed. Select the browser which you want to test and click OK.

Step 3
Hit the ctrl+ F5 or select "Start Without Debugging" option under the Debug menu. The application will be opened with all selected browsers.

 

6) Convert JSON And XML Object Into Class
Visual Studio has a super cool feature which is to generate the classes from a JSON/XML object using just copy-paste. Please refer to my other article about the details of this feature.

In this article, we have learned about various Visual Studio hidden features which help us to improve our productivity.



About HostForLIFE

HostForLIFE is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2019 Hosting, ASP.NET 5 Hosting, ASP.NET MVC 6 Hosting and SQL 2019 Hosting.


Tag cloud

Sign in