这些方法的优缺点是什么 SQL 服务器繁琐的查询
What is pros and cons for these approaches SQL Server tedious queries
这两个查询,一个没有输入参数,一个有输入参数,各有什么优缺点。
方法一:
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);
方法#2:使用输入参数
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);
哪个更安全?
第二个版本更安全,查询字符串是常量,因此SQL服务器需要解析和验证查询的次数更少,参数类型也明确设置。
在下面的测试中:
const TDS = require("tedious")
const body = {
LastName: "A",
FirstName: "B"
}
var request = new TDS.Request(
`INSERT INTO TableName (LastName, FirstName)
VALUES ('${body.LastName}', '${body.FirstName}')`);
let parmRequest = new TDS.Request(
`INSERT INTO TableName (LastName, FirstName)
VALUES (@LastName, @FirstName)`);
parmRequest.addParameter('LastName', TDS.TYPES.VarChar, body.LastName)
parmRequest.addParameter('FirstName', TDS.TYPES.VarChar, body.FirstName)
console.log(request);
console.log(parmRequest);
第一个查询只是插入的字符串,不包含任何参数,因此SQL服务器每次需要执行时都会将此查询视为新查询,需要对其进行解析和验证。
第二种方法肯定更安全,因为在第一种方法中你只使用字符串插值,这可以被认为是简单的字符串连接。
其次不允许恶意输入,因此防止SQL注入。
这两个查询,一个没有输入参数,一个有输入参数,各有什么优缺点。
方法一:
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);
方法#2:使用输入参数
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);
哪个更安全?
第二个版本更安全,查询字符串是常量,因此SQL服务器需要解析和验证查询的次数更少,参数类型也明确设置。
在下面的测试中:
const TDS = require("tedious")
const body = {
LastName: "A",
FirstName: "B"
}
var request = new TDS.Request(
`INSERT INTO TableName (LastName, FirstName)
VALUES ('${body.LastName}', '${body.FirstName}')`);
let parmRequest = new TDS.Request(
`INSERT INTO TableName (LastName, FirstName)
VALUES (@LastName, @FirstName)`);
parmRequest.addParameter('LastName', TDS.TYPES.VarChar, body.LastName)
parmRequest.addParameter('FirstName', TDS.TYPES.VarChar, body.FirstName)
console.log(request);
console.log(parmRequest);
第一个查询只是插入的字符串,不包含任何参数,因此SQL服务器每次需要执行时都会将此查询视为新查询,需要对其进行解析和验证。
第二种方法肯定更安全,因为在第一种方法中你只使用字符串插值,这可以被认为是简单的字符串连接。
其次不允许恶意输入,因此防止SQL注入。