I am working on a TS/NodeJS/MSSQL project and I basically want to iterate an array of something, let's say products, run a select query to determine if said product is in the database and if not insert it.
The purpose of this exercise is to use prepared statements for both the select, insert and be able to reuse them in the loop iterating the products.
So let's say we have array of this:
export interface IProduct{
name:string;
price:number;
}
then we create the connection:
const mssql = require(mssql);
let connection = new mssql.ConnectionPool({
server:[server address],
database:[database name],
user:[username],
password:[password]
});
then the prepared queries
let insertQuery = new msssql.PreparedStatement(connection);
insertQuery.input("name",mssql.TYPES.NVarChar);
insertQuery.input("price",mssql.TYPES.Float);
then let's iterate the products array:
async iterateProducts(products:Array<IProduct>){
//first prepare the query if it's not prepared
if(!insertQuery.prepared)
await insertQuery.prepare("INSERT INTO Products (name,price) values (@name,@price)");
products.forEach(async (p)=>{
let insertResult = await insertQuery.execute(p);
//do anything after insert
});
}
//then unprepare query
await insertQuery.unprepare();
The error I keep getting is
Can't acquire connection for the request. There is another request in progress
I am really new to this stuff, so there is a big chance I am totally missing something obvious or misusing it somehow.
Note: Code is pseudo-code, just describing the problem. Don't take it as production working code. So if there is a dot or comma or anything missing or wrong, it's probably ok.
Any help would be greatly appreciated. Thanks!