我团队的一位高级开发人员告诉我,像这样编写 SQL 命令是安全的 "because it's parameterized",但我不明白如何

A senior developer on my team tells me that writing SQL commands like this is safe "because it's parameterized", but I don't see how

我正在为与某些产品相关的媒体编写一些 CRUD 函数。要删除许多记录,有人告诉我按如下方式编写查询:

dataContext.ExecuteCommand("DELETE FROM ProductMedia WHERE ProductId = {0}", productId);

他说这对 SQL 注射是安全的,因为它是 'parameterized'。我不同意,但我也不知道更好的方法。

用这种方式编写命令时如何防止SQL注入?

He says this is safe from SQL injection because it's 'parameterized'.

根据 the docs,您问题中的代码完全有效并且将被正确参数化:

The syntax for the command is almost the same as the syntax used to create an ADO.NET DataCommand. The only difference is in how the parameters are specified. Specifically, you specify parameters by enclosing them in braces ({…}) and enumerate them starting from 0. The parameter is associated with the equally numbered object in the parameters array.

它本质上是一个包装器 - 它负责创建必要的 SqlParameter 对象并为它们赋值。其他 ORM(如 PetaPoco)也有类似的机制。

通常,您要避免的事情是 字符串连接 (或有效连接的东西 - 如 string.Format)- 此解决方案不使用。字符串连接 几乎总是 对 SQL 注入开放。 但是,同样,您问题中的代码没问题。