Salim Shamim
Salim Shamim

Reputation: 686

Insert multiple records into SQL Server (mssql) in node.js

I am migrating a piece of code from mysql to mssql package of nodejs, in which its required to insert multiple rows.

Here's the sample code I am using for testing:

const db = require('mssql');

let config = {
    user: 'salim',
    password: 'admin',
    server: 'LAPTOP-JK45R', // You can use 'localhost\\instance' to connect to named instance
    database: 'master',
}

var pool;

//initialize connection pool
var connectPool = initializeConnectionPool();

function initializeConnectionPool() {
    pool = new db.ConnectionPool(config);
    pool.on('error', (err) => {
        logger.error(err);
    });

    return pool.connect();;
}

connectPool.then(async () => {
    let connection = await pool.request();
    console.log('Got pool connection...');
    var q = "INSERT INTO Person (name, address) VALUES ?";
    
    var values = [
        ['John', 'Highway 71'],
        ['Peter', 'Lowstreet 4'],
        ['Amy', 'Apple st 652'],
        ['Hannah', 'Mountain 21']
    ];

    let result = await connection.query(q,[values]);

    console.log(`Result: ${JSON.stringify(result)}`);
});

Its giving me error:

RequestError: Incorrect syntax near '?'.

I couldn't find any thing on official npm page of mssql, so I have been trying this: Insert multiple columns and rows into SQL Server with node js

In my code I am just using pool.

I also couldn't find how to log queries using this package, so couldn't figure out what the query is being formed.

It would be great to know any of the solution.

Upvotes: 0

Views: 2321

Answers (1)

Antonin Riche
Antonin Riche

Reputation: 568

The ? is a way to pass parameter in mysql

In mssql it seem to be like ${entries}

refer to How to pass parameter to mssql query in node js

Upvotes: 1

Related Questions