最近我遇到了类似下面的代码:
string insertSql = "";
foreach (int animalType in new[] { 1,2,3 })
insertSql += String.Format("INSERT INTO `animalType` (type) VALUES ({0}); ", animalType);
每次插入的数量很少(1-3)。
感觉“不好”,但我不能确切地说出原因。有什么想法吗?
基本上很多sql插入被连接成一个字符串。据我所知,不通过字符串连接向 sql 添加值的原因有 3 个:安全性、格式问题、执行速度。因为参数是int,所以不能有任何sql注入(inject)。没有格式问题需要处理。此外,因为这些是插入,sql server 不会重用句柄(afaik 它存储并可选择重用查询句柄)。
此外, table 上没有触发器。
通常可以通过使用 union INSERT INTO animalType (type) (SELECT 1 UNION SELECT 2 UNION SELECT 3)
进行单次插入来改进。
我知道可以使用数据表并将其添加到参数化查询中,或者可以使用 xml,但这不会使代码变得更长且更难阅读吗? 我只是没有任何真正的反对意见。
以这种方式动态创建参数化查询是否有任何意义:
string insertSql = "";
SqlCommand command = new SqlCommand();
var types = new[] { 1, 2, 3 };
for (int i = 0; i < types.Length; i++)
{
insertSql += String.Format("INSERT INTO `animalType` (type) VALUES (@typeParam{0}); ", i);
command.Parameters.AddWithValue("typeParam" + i, types[i]);
}
我能对连接 sql 整数值而不使用参数化查询的人说些什么,因为他的方法更简单? :)
最佳答案
您可以对其进行概要分析以确保确定,但我敢打赌您不会因为多次执行一个命令而显着获得更差的性能:
string insertSql = "INSERT INTO animalType (type) VALUES (@type)";
var types = new[] { 1, 2, 3 };
using(SqlCommand command = new SqlCommand(insertSql, conn))
{
foreach(var type in types)
{
command.Parameters.AddWithValue("@type", type);
command.ExecuteNonQuery();
}
}
What can I say to a person concatenating sql integer values and not using parametrized queries because his method is simpler?
我的论点是,让代码容易受到 SQL 注入(inject)和格式问题的攻击并不需要太多。在您添加字符串列的那一刻,代码很容易受到攻击,下一个添加字符串列的人很可能不会花时间将查询转换为参数化,只是为了添加一列。
关于c# mssql sql连接和多个插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23957488/