I am curious what the difference is between queries and prepared statements in npm mssql .
They look the same to me, as most importantly they both sanitize the input.
The query looks simpler to write, but what do I not know? Why use the one over the other?
Query
const sql = require('mssql')
(async function () {
try {
let pool = await sql.connect(config)
let result = await pool.request()
.input('input_parameter', sql.Int, value)
.query('select * from mytable where id = @input_parameter')
console.dir(result)
} catch (err) {
// ... error checks
}
})()
Prepared statement
const ps = new sql.PreparedStatement(/* [pool] */)
ps.input('param', sql.Int)
ps.prepare('select @param as value', err => {
// ... error checks
ps.execute({param: 12345}, (err, result) => {
// ... error checks
// release the connection after queries are executed
ps.unprepare(err => {
// ... error checks
})
})
})
1条答案
按热度按时间fslejnso1#
For a one time select, there is little benefit from using a prepared statement vs a query with bound parameters. However, if you are running a query many times, like updated thousands of rows, preparing that statement outside a loop and running it inside the loop can give a pretty large performance boost.