DEV Community

yashrajsinh chauhan
yashrajsinh chauhan

Posted on

2

How to Connect MSSQL with Node.js

This article is about How we can connect nodejs and mssql

In this tutorial, we'll explore how to connect Microsoft SQL Server (MSSQL) with Node.js using the Express framework to create an API. We'll use NPM (Node Package Manager) to install the necessary packages.

Prerequisites: Ensure you have Node.js installed on your machine.

  • Setting Up the Project
  • Create a new folder named dbConnection and open it in your code editor (e.g., VSCode).
  • Initialize a new Node.js project by running npm init in the terminal. Press Enter for default options or use npm init -y for quick initialization.
  • Install the required packages: npm install express mssql. This will add express and mssql to your project's package.json file.

data

  • Creating the Server Create a JavaScript file named server.js and write the following code:

javascript

const express = require("express");
const sql = require("mssql");

const app = express();

// SQL Server configuration
var config = {
"user": " ", // Database username
"password": " ", // Database password
"server": " ", // Server IP address
"database": "Training", // Database name
"options": {
"encrypt": false // Disable encryption
}
}

// Connect to SQL Server
sql.connect(config, err => {
if (err) {
throw err;
}
console.log("Connection Successful!");
});

// Define route for fetching data from SQL Server
app.get("/", (request, response) => {
// Execute a SELECT query
new sql.Request().query("SELECT * FROM Employee", (err, result) => {
if (err) {
console.error("Error executing query:", err);
} else {
response.send(result.recordset); // Send query result as response
console.dir(result.recordset);
}
});
});

// Start the server on port 3000
app.listen(3000, () => {
console.log("Listening on port 3000...");
});

Output of the code

Explanation
We use the express and mssql packages to set up an Express server and establish a connection to MSSQL database, respectively.

The config object contains the database connection details, including the username, password, server IP, and database name. The encrypt option is set to false to disable encryption for the connection.

After establishing the connection, we define a route (/) to fetch data from the "Employee" table in the database. When this route is accessed, a SELECT query is executed to retrieve all records from the table. The query result is sent back as the response to the client.

Finally, the server is started on port 3000, and a message indicating successful startup is logged to the console.

With this setup, you can access the API endpoint (http://localhost:3000) in your browser or send HTTP requests to fetch data from the MSSQL database.

That's it! You've successfully connected MSSQL with Node.js using Express.

Now you are ready to apply in GOOGLE. 😊

NodeJS #MSSQL #Express #API #Database #Tutorial #Programming #Development #WebDevelopment #Backend #SQLServer #NodePackageManager #NPM #JavaScript #Code #SoftwareDevelopment #TechTutorial

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay