Search code examples
sqlnode.jssql-servertediousnode-mssql

What is pros and cons for these approaches SQL Server tedious queries


What are the pros in cons between these two queries one without input parameters and the other one with input parameters.

Method #1:

 const pool = await poolPromise;
 const request = await pool.request()
 let CustomQuery = `INSERT INTO TableName (LastName, FirstName) 
                    VALUES ('${body.LastName}', '${body.FirstName}'`;

 const result = await request.query(CustomQuery);

Method #2: using input parameters

 const pool = await poolPromise;
 const request = await pool.request()
      .input('LastName', TYPES.VarChar, body.LastName)
      .input('FirstName', TYPES.VarChar, body.FirstName)

 let CustomQuery = `INSERT INTO TableName (LastName, FirstName) 
                    VALUES (@LastName, @FirstName)`
 const result = await request.query(CustomQuery);

Which is safer?


Solution

  • Second is dfinietely safer, as in first approach you just use string interpolation, which can be thought of as simple string concatenation.

    Second won't allow malicious input, therefore prevent SQL injection.

    See SQL injection.