0

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.

Dale K
  • 25,246
  • 15
  • 42
  • 71
Salim Shamim
  • 656
  • 10
  • 25

1 Answers1

1

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

Antonin Riche
  • 548
  • 6
  • 10
  • SQL Server also supports prepared statement parameters. Building SQL out of strings is not good advice. – Pointy Aug 09 '20 at 14:04
  • Indeed, but as I saw, it seems to be a different way than with mysql (with `?`) – Antonin Riche Aug 09 '20 at 14:08
  • There could be n number of rows and the idea of building strings using those values doesn't seems a thing one would do in production, I want to know how is it possible as it is in `mysql` ? – Salim Shamim Aug 09 '20 at 14:56