In this post, we will see how we can perform CRUD application in our SQL database using Node JS. As you all know, Node JS is a run time environment built on Chrome’s V8 JavaScript engine for server side and networking application. And it is an open source which supports cross platforms. Node JS applications are written in pure JavaScript. If you are new to Node JS, I strongly recommend you read my previous post about Node JS here. Now let’s begin.
Background
There was a time where we developers were dependant on any server side languages to perform server side actions. Few years ago, a company called Joyent, Inc. brought us a solution for this. That is, we can do the server side actions if we know JavaScript. Because of the wonderful idea behind this, it became a great success. You can do server side actions without knowing a single code related to any server side languages like C# and PHP. Here, we are going to see how you can do the database actions like Create, Read, Update, Delete using Node JS. I hope you will like this.
Before we start coding our Node JS application, we can set up Node JS tool available for Visual Studio.
Node JS Tool for Visual Studio
You can always run your Node JS code by using a command prompt, so setting up this tool is optional. If you install it, you can easily debug and develop Node JS. So I recommend you install it.
To download the tool, please click on this link. Once you have downloaded the set up file, you can start installing it.
So I hope you have installed the application. Now, you can create a Node JS application in our Visual Studio.
Creating Node JS Application In Visual Studio
You can find an option as Node JS in your Add New Project window as follows. Please click on that and create a new project.
Now our Visual Studio is ready for coding, but as I mentioned earlier, we are going to use SQL Server as our database. So we need to do some configuration related to that too. Let’s do it now.
Configure SQL Server for Node JS Development
You need to make sure that the following services are run:
- SQL Server
- SQL Server Agent (Skip it if you are using SQLEXPRESS)
- SQL Server Browser
To check the status of these services, you can always do so by running services.msc in Run command window. Once you are done, you need to enable some protocols and assign a port to it. Now go to your SQL Server Configuration Manager. Most probably, you can find the file in this C:\Windows\SysWOW64 location, if you can't find it, start window.
Now go to SQL Server Network Configuration and click on Protocols for SQLEXPRESS(Your SQL Server) and Enable TCP/IP.
Now right click and click on Properties on TCP/IP. Go to IP Addresses and assign port for all the IPs.
If you have done it, it is time to set up your database and insert some data. Please do not forget to restart your service, as it is mandatory to get updated the changes we have done in the configurations.
Creating Database
Here, I am creating a database with name “TrialDB
”, you can always create a DB by running the query given below:
USE [master]
GO
CREATE DATABASE [TrialDB]
CONTAINMENT = NONE
ON PRIMARY
( NAME = N'TrialDB', FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL13.SQLEXPRESS\MSSQL\DATA\TrialDB.mdf' , _
SIZE = 8192KB , MAXSIZE = UNLIMITED, FILEGROWTH = 65536KB )
LOG ON
( NAME = N'TrialDB_log', _
FILENAME = N'C:\Program Files\Microsoft SQL Server\
MSSQL13.SQLEXPRESS\MSSQL\DATA\TrialDB_log.ldf' , _
SIZE = 8192KB , MAXSIZE = 2048GB , FILEGROWTH = 65536KB )
GO
ALTER DATABASE [TrialDB] SET COMPATIBILITY_LEVEL = 130
GO
IF (1 = FULLTEXTSERVICEPROPERTY('IsFullTextInstalled'))
begin
EXEC [TrialDB].[dbo].[sp_fulltext_database] @action = 'enable'
end
GO
ALTER DATABASE [TrialDB] SET ANSI_NULL_DEFAULT OFF
GO
ALTER DATABASE [TrialDB] SET ANSI_NULLS OFF
GO
ALTER DATABASE [TrialDB] SET ANSI_PADDING OFF
GO
ALTER DATABASE [TrialDB] SET ANSI_WARNINGS OFF
GO
ALTER DATABASE [TrialDB] SET ARITHABORT OFF
GO
ALTER DATABASE [TrialDB] SET AUTO_CLOSE OFF
GO
ALTER DATABASE [TrialDB] SET AUTO_SHRINK OFF
GO
ALTER DATABASE [TrialDB] SET AUTO_UPDATE_STATISTICS ON
GO
ALTER DATABASE [TrialDB] SET CURSOR_CLOSE_ON_COMMIT OFF
GO
ALTER DATABASE [TrialDB] SET CURSOR_DEFAULT GLOBAL
GO
ALTER DATABASE [TrialDB] SET CONCAT_NULL_YIELDS_NULL OFF
GO
ALTER DATABASE [TrialDB] SET NUMERIC_ROUNDABORT OFF
GO
ALTER DATABASE [TrialDB] SET QUOTED_IDENTIFIER OFF
GO
ALTER DATABASE [TrialDB] SET RECURSIVE_TRIGGERS OFF
GO
ALTER DATABASE [TrialDB] SET DISABLE_BROKER
GO
ALTER DATABASE [TrialDB] SET AUTO_UPDATE_STATISTICS_ASYNC OFF
GO
ALTER DATABASE [TrialDB] SET DATE_CORRELATION_OPTIMIZATION OFF
GO
ALTER DATABASE [TrialDB] SET TRUSTWORTHY OFF
GO
ALTER DATABASE [TrialDB] SET ALLOW_SNAPSHOT_ISOLATION OFF
GO
ALTER DATABASE [TrialDB] SET PARAMETERIZATION SIMPLE
GO
ALTER DATABASE [TrialDB] SET READ_COMMITTED_SNAPSHOT OFF
GO
ALTER DATABASE [TrialDB] SET HONOR_BROKER_PRIORITY OFF
GO
ALTER DATABASE [TrialDB] SET RECOVERY SIMPLE
GO
ALTER DATABASE [TrialDB] SET MULTI_USER
GO
ALTER DATABASE [TrialDB] SET PAGE_VERIFY CHECKSUM
GO
ALTER DATABASE [TrialDB] SET DB_CHAINING OFF
GO
ALTER DATABASE [TrialDB] SET FILESTREAM( NON_TRANSACTED_ACCESS = OFF )
GO
ALTER DATABASE [TrialDB] SET TARGET_RECOVERY_TIME = 60 SECONDS
GO
ALTER DATABASE [TrialDB] SET DELAYED_DURABILITY = DISABLED
GO
ALTER DATABASE [TrialDB] SET QUERY_STORE = OFF
GO
USE [TrialDB]
GO
ALTER DATABASE SCOPED CONFIGURATION SET MAXDOP = 0;
GO
ALTER DATABASE SCOPED CONFIGURATION FOR SECONDARY SET MAXDOP = PRIMARY;
GO
ALTER DATABASE SCOPED CONFIGURATION _
SET LEGACY_CARDINALITY_ESTIMATION = OFF;
GO
ALTER DATABASE SCOPED CONFIGURATION FOR _
SECONDARY SET LEGACY_CARDINALITY_ESTIMATION = PRIMARY;
GO
ALTER DATABASE SCOPED CONFIGURATION SET PARAMETER_SNIFFING = ON;
GO
ALTER DATABASE SCOPED CONFIGURATION FOR _
SECONDARY SET PARAMETER_SNIFFING = PRIMARY;
GO
ALTER DATABASE SCOPED CONFIGURATION SET QUERY_OPTIMIZER_HOTFIXES = OFF;
GO
ALTER DATABASE SCOPED CONFIGURATION FOR _
SECONDARY SET QUERY_OPTIMIZER_HOTFIXES = PRIMARY;
GO
ALTER DATABASE [TrialDB] SET READ_WRITE
GO
Create a Table and Insert Data in Database
To create a table, you can run the query below:
USE [TrialDB]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Course](
[CourseID] [int] NOT NULL,
[CourseName] [nvarchar](50) NOT NULL,
[CourseDescription] [nvarchar](100) NULL,
CONSTRAINT [PK_Course] PRIMARY KEY CLUSTERED
(
[CourseID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, _
ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
Now, we can insert a little data to our newly created table.
USE [TrialDB]
GO
INSERT INTO [dbo].[Course]
([CourseID]
,[CourseName]
,[CourseDescription])
VALUES
(1
,'C#'
,'Learn C# in 7 days')
INSERT INTO [dbo].[Course]
([CourseID]
,[CourseName]
,[CourseDescription])
VALUES
(2
,'Asp.Net'
,'Learn Asp.Net in 7 days')
INSERT INTO [dbo].[Course]
([CourseID]
,[CourseName]
,[CourseDescription])
VALUES
(3
,'SQL'
,'Learn SQL in 7 days')
INSERT INTO [dbo].[Course]
([CourseID]
,[CourseName]
,[CourseDescription])
VALUES
(4
,'JavaScript'
,'Learn JavaScript in 7 days')
GO
So our data is ready, that means we are all set to write our Node JS application. Go to the application we created and you can see a JS file there, normally named as server.js. Here, I am going to change the name as App.js.
MSSQL – Microsoft SQL Server Client for Node.js
You can find many packages for our day to day life in Node JS, what you need to do all is, just install that package and start using it. Here, we are going to use a package called MSSQL.
Node-MSSQL
- has unified interface for multiple TDS drivers.
- has built-in connection pooling.
- supports built-in JSON serialization introduced in SQL Server 2016.
- supports Stored Procedures, Transactions, Prepared Statements, Bulk Load and TVP.
- supports serialization of Geography and Geometry CLR types.
- has smart JS data type to SQL data type mapper.
- supports Promises, Streams and standard callbacks.
- supports ES6 tagged template literals.
- is stable and tested in production environment.
- is well documented.
You can find more about the package here. You can easily install this package by running the following command in your Nuget Package Manager Console.
npm install mssql
Now we can load this package by using a function called require
.
var sqlInstance = require("mssql");
Then, you can set the database configurations as follows.
/Database configuration
var setUp = {
server: 'localhost',
database: 'TrialDB',
user: 'sa',
password: 'sa',
port: 1433
};
Once you have a configuration set up, you can connect your database by using connect()
function.
sqlInstance.connect(setUp)
Now, we can perform the CRUD operations. Are you ready?
Select All the Data from Database using Node JS
new sqlInstance.Request()
.query("select * from Course")
.then(function (dbData) {
if (dbData == null || dbData.length === 0)
return;
console.dir('All the courses');
console.dir(dbData);
})
.catch(function (error) {
console.dir(error);
});
Now, run your application and see the output as follows:
Select Data with Where Condition from Database using Node JS
You can always select a particular record by giving an appropriate select
query as follows:
var value = 2;
new sqlInstance.Request()
.input("param", sqlInstance.Int, value)
.query("select * from Course where CourseID = @param")
.then(function (dbData) {
if (dbData == null || dbData.length === 0)
return;
console.dir('Course with ID = 2');
console.dir(dbData);
})
.catch(function (error) {
console.dir(error);
});
So what would be the output of the above code? Any idea?
Insert Data to Database using Node JS
We can always perform some insert
query too using Node JS, the difference here will be, as we have Transactions in SQL, we will include that too here. The following code performs an insert
operation.
var dbConn = new sqlInstance.Connection(setUp,
function (err) {
var myTransaction = new sqlInstance.Transaction(dbConn);
myTransaction.begin(function (error) {
var rollBack = false;
myTransaction.on('rollback',
function (aborted) {
rollBack = true;
});
new sqlInstance.Request(myTransaction)
.query("INSERT INTO [dbo].[Course]
([CourseName],[CourseDescription])
VALUES ('Node js',
'Learn Node JS in 7 days')",
function (err, recordset) {
if (err) {
if (!rollBack) {
myTransaction.rollback(function (err) {
console.dir(err);
});
}
} else {
myTransaction.commit().then(function (recordset) {
console.dir('Data is inserted successfully!');
}).catch(function (err) {
console.dir('Error in transaction commit ' + err);
});
}
});
});
});
So let’s run it and see the output.
Delete Data from Database using Node JS
As we performed insert
operation, we can do the same for delete
operation as below:
var delValue = 4;
var dbConn = new sqlInstance.Connection(setUp,
function (err) {
var myTransaction = new sqlInstance.Transaction(dbConn);
myTransaction.begin(function (error) {
var rollBack = false;
myTransaction.on('rollback',
function (aborted) {
rollBack = true;
});
new sqlInstance.Request(myTransaction)
.query("DELETE FROM [dbo].[Course]
WHERE CourseID=" + delValue,
function (err, recordset) {
if (err) {
if (!rollBack) {
myTransaction.rollback(function (err) {
console.dir(err);
});
}
} else {
myTransaction.commit().then(function (recordset) {
console.dir('Data is deleted successfully!');
}).catch(function (err) {
console.dir('Error in transaction commit ' + err);
});
}
});
});
});
Now, run your application and see whether the data is deleted.
Update Data from Database using Node JS
The only action pending here to perform is UPDATE
. Am I right? Let’s do that too.
var updValue = 3;
var dbConn = new sqlInstance.Connection(setUp,
function (err) {
var myTransaction = new sqlInstance.Transaction(dbConn);
myTransaction.begin(function (error) {
var rollBack = false;
myTransaction.on('rollback',
function (aborted) {
rollBack = true;
});
new sqlInstance.Request(myTransaction)
.query("UPDATE [dbo].[Course] SET [CourseName] = 'Test' _
WHERE CourseID=" + updValue,
function (err, recordset) {
if (err) {
if (!rollBack) {
myTransaction.rollback(function (err) {
console.dir(err);
});
}
} else {
myTransaction.commit().then(function (recordset) {
console.dir('Data is updated successfully!');
}).catch(function (err) {
console.dir('Error in transaction commit ' + err);
});
}
});
});
});
Here goes the output:
You can always download the source code attached to see the complete code and application. Happy coding!.
See Also
Conclusion
Did I miss anything that you may think is needed? Could you find this post useful? I hope you liked this article. Please share your valuable suggestions and feedback.
Your Turn. What Do You Think?
A blog isn’t a blog without comments, but do try to stay on topic. If you have a question unrelated to this post, you’re better off posting it on C# Corner, Code Project, Stack Overflow, ASP.NET Forum instead of commenting here. Tweet or email me a link to your question there and I’ll definitely try to help if I can.