Open In App

How to connect SQL Server database from JavaScript in the browser ?

Improve
Improve
Like Article
Like
Save
Share
Report

There is no common way to connect to the SQL Server database from a JavaScript client, every browser has its own API and packages to connect to SQL Server. For example, in the Windows operating system, Internet Explorer has a class name called ActiveXObject which is used to create instances of OLE Automation objects, and these objects help us to create an environment for SQL Driver connection. 

It is not recommended to use JavaScript clients to access databases for several reasons. For example, it is not good practice, there are some security issues and it offers vulnerabilities issues.

Node.js provides us with an environment to run JavaScript code outside the browser and also it offers useful benefits like security, scalability, robustness, and many more. 

SQL Server: Microsoft SQL Server is a relational database management system developed by Microsoft. As a database server, it is a software product with the primary function of storing and retrieving data as requested by other software applications—which may run either on the same computer or on another computer across a network. 

Node.Js: Node.js is an open-source, cross-platform, JavaScript runtime environment that executes JavaScript code outside a web browser.

Here, We are representing the connection of the MS SQL Server database using JavaScript in the Node.js environment. To get started we need to install certain packages and MS SQL Server Node.js must be installed in the local system.

It’s strongly recommended to use any command-line tool(CLI) like terminal, or cmd to run the following queries and commands.

Before getting started MS SQL Server should be installed in the local system. 

Hit the listed command to get connect with SQL Server.

sqlcmd -S localhost -U SA -P "<password>"

Issue listed queries to create a database name called ‘geek’.

> CREATE DATABASE geek;
> GO
  • To use created data issue listed queries.
> Use <your database name>;
> GO

Issue listed queries to create a table name called ‘student’ with three fields id, firstname, and lastname.

> CREATE TABLE student (id INT, 
    firstname NVARCHAR(30), lastname NVARCHAR(30));
> GO

Issue listed queries to insert some values into table ‘student’.

> INSERT INTO student VALUES (1, 'Stephen', 'Hawking');
> INSERT INTO student VALUES (2, 'Isaac', 'Newton');
> INSERT INTO student VALUES (3, 'Chandrasekhara Venkata', 'Raman');
> GO

To check entries of table issue listed queries.

> SELECT * from student;
> GO

Before getting started Node.js should be installed in the local system. 

To create a Node.js environment issue follow the command.

npm init

Express allows us to set up middlewares to respond to HTTP Requests.

npm install express --save

Microsoft SQL Server client gives us functionality to connect with SQL server.

npm install mssql --save

To begin with the Node.js part, we need to create our server file server.js in our local system.

javascript




// Requiring modules
const express = require('express');
const app = express();
const mssql = require("mysql");
 
// Get request
app.get('/', function (req, res) {
 
    // Config your database credential
    const config = {
        user: 'SA',
        password: 'Your_Password',
        server: 'localhost',
        database: 'geek'
    };
 
    // Connect to your database
    mssql.connect(config, function (err) {
 
        // Create Request object to perform
        // query operation
        let request = new mssql.Request();
 
        // Query to the database and get the records
        request.query('select * from student',
            function (err, records) {
 
                if (err) console.log(err)
 
                // Send records as a response
                // to browser
                res.send(records);
 
            });
    });
});
 
let server = app.listen(5000, function () {
    console.log('Server is listening at port 5000...');
});


Run the server.js file using the following command:  

node server.js

After executing the above command, you will see the following output on your console:  

Server is listening at port 5000...

Now hit the URL http://localhost:5000/ in the local browser.

Output:



Last Updated : 05 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads