[ Web Proxy ]
URL:
Viewing: https://www.sqlservertutorial.net/nodejs-sql-server/nodejs-sql-server-update/ [Back]  [Original]

Node.js SQL Server: Update
Skip to content

Node.js SQL Server: Update

Savigo [Savigo]
You organize your data. Now organize your savings.
Set savings goals, track your progress, and stay on course.
Get Savigo for iPhone 

Summary: in this tutorial, you will learn how to update data in SQL Server from Node.js applications.

This tutorial begins wherethe Performing a Bulk Insert from Node.js tutorialleft off.

We’ll show you how to update the author’s first name in the Authors table.

Updating data in a table #

Step 1. Create a new file called update.js in the project directory.

Step 2. Define a new function updateAuthor in the update.js file to update the author’s first name:

import sql from 'mssql';
import { config } from './config.js';

export const updateAuthor = async (id, firstName) => {
  try {
    // Connect to the database
    await sql.connect(config);

    // Update the First Name
    const result =
      await sql.query`UPDATE Authors SET FirstName =${firstName} WHERE AuthorID=${id}`;

    console.dir(result);
  } catch (err) {
    console.error(err);
  }
};Code language: JavaScript (javascript)

How it works.

First, import the sql object from the mssql module and the config object from the config.js module respectively:

import sql from 'mssql';
import { config } from './config.js';Code language: JavaScript (javascript)

Note that the config object contains all the database parameters including server, database name, username, and password.

Second, define an updateAuthor function that updates the first name of an author specified by an id:

export const updateAuthor = async (id, firstName) => {Code language: JavaScript (javascript)

Third, connect to the SQL Server using the connect() method of the sql object:

await sql.connect(config);Code language: JavaScript (javascript)

Fourth, execute an UPDATE statement to change the name of the author specified by the author id to the new one:

const result =
      await sql.query`UPDATE Authors SET FirstName =${firstName} WHERE AuthorID=${id}`;Code language: JavaScript (javascript)

Fifth, display the result if the query is executed successfully:

console.dir(result);Code language: JavaScript (javascript)

The result object contains the number of rows updated. To access it, you use the rowsAffected property:

result.rowsAffectedCode language: JavaScript (javascript)

It is an array of numbers indicating the row affected by statements. To access the rows affected by the first statement, you can access the first element of the result.rowsAffected array:

if (result.rowsAffected.length >= 1) {
  console.log(`Row(s) affected: ${result.rowsAffected[0]}`);
}Code language: JavaScript (javascript)

Step 3. Import the updateAuthor from the update.js module and call it to update the first name of the author with id 14 to 'Joanne Kathleen':

import { updateAuthor } from './update.js';

await updateAuthor(14, 'Joanne Kathleen');Code language: JavaScript (javascript)

Step 4. Open the terminal and run the following command to run the index.js file:

npm startCode language: JavaScript (javascript)

If you see the following output, you have successfully updated the row:

{
  recordsets: [],
  recordset: undefined,
  output: {},
  rowsAffected: [ 1 ]
}Code language: JavaScript (javascript)

The output indicates that the rowsAffected contains the number 1, meaning that one row has been updated successfully.

Here’s the detailed information on the properties of the result object:

Updating data using parameters #

The following redefines the updateAuthor that uses parameters to update the first name of an author specified by an ID:

import sql from 'mssql';
import { config } from './config.js';

export const updateAuthor = async (id, firstName) => {
  try {
    // Connect to the database
    const pool = await sql.connect(config);

    // Update the First Name
    const result = await pool
      .request()
      .input('id', sql.Int, id)
      .input('firstName', sql.VarChar, firstName)
      .query(`UPDATE Authors SET FirstName =@firstName WHERE AuthorID=@id`);

    if (result.rowsAffected.length >= 1) {
      console.log(`${result.rowsAffected.length} row(s) updated!`);
    }
  } catch (err) {
    console.error(err);
  }
};Code language: JavaScript (javascript)

How it works.

First, open a connection to the SQL Server:

const pool = await sql.connect(config);Code language: JavaScript (javascript)

The connect() method returns a ConnectionPool object.

Second, execute an UPDATE statement by executing the query method and binding parameters using the input() method:

const result = await pool
  .request()
  .input('id', sql.Int, id)
  .input('firstName', sql.VarChar, firstName)
  .query(`UPDATE Authors SET FirstName =@firstName WHERE AuthorID=@id`);Code language: JavaScript (javascript)

In this statement, the @firstName and @id are parameter holders. They will be replaced by the value of the parameters id and firstName provided to input() methods respectively.

The query() method returns a result object that contains the same information as the sql.query tagged template literals.

Third, display a number of updated rows:

if (result.rowsAffected.length >= 1) {
  console.log(`${result.rowsAffected.length} row(s) updated!`);
}Code language: JavaScript (javascript)

Download the project source code #

Download the project source code

Summary #

Was this tutorial helpful?
Yes No

Copyright © 2025 by www.sqlservertutorial.net. All Rights Reserved.

Microsoft Corporation does not sponsor the tutorials on sqlservertutorial.net, and this website has no relationship with Microsoft Corporation.

Web Proxy Viewer  |  New URL  |  Original Page