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.

4
  • Perhaps there's something in the Node SQL Server interface that differs from my experience, but your VALUES clause should be a list of parenthesized lists like (?, ?), one for each row. Commented Aug 9, 2020 at 14:16
  • There would be x number of rows and (?,?) would be possible if I make string adding to it in each iteration. Commented Aug 9, 2020 at 14:58
  • Could you solve it? @SalimShamim Commented Dec 15, 2021 at 15:18
  • @MartínJF I think I used backticks (````)and replaced value in query Commented Dec 19, 2021 at 10:07

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

3 Comments

SQL Server also supports prepared statement parameters. Building SQL out of strings is not good advice.
Indeed, but as I saw, it seems to be a different way than with mysql (with ?)
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 ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.