我的课本说:
”参数化查询的执行速度通常比文字SQL字符串快得多 因为它们仅被解析一次(而不是每次都将SQL字符串分配给CommandText属性)。”
我很困惑,假设我们有一个插入方法
public void InsertAuto(Car car)
{
OpenConnection();
// Format and execute SQL statement.
string sql = "Insert Into Inventory (Make, Color, PetName) Values " +
$"('{car.Make}', '{car.Color}', '{car.PetName}')";
// Execute using our connection.
using (SqlCommand command = new SqlCommand(sql, _sqlConnection))
{
command.CommandType = CommandType.Text;
command.ExecuteNonQuery();
}
CloseConnection();
}
难道sql字符串文字被构造一次且简单明了吗?
如果您以这种方式这样做:
public void InsertAuto(Car car)
{
OpenConnection();
// Format and execute SQL statement.
string sql = "Insert Into Inventory" + "(Make, Color, PetName) Values" + "(@Make, @Color, @PetName)"; // Execute using our connection.
using (SqlCommand command = new SqlCommand(sql, _sqlConnection))
{
SqlParameter parameter = new SqlParameter
{
ParameterName = "@Make",
Value = car.Make,
SqlDbType = SqlDbType.Char,
Size = 10
};
command.Parameters.Add(parameter);
parameter = new SqlParameter
{
ParameterName = "@Color",
Value = car.Color,
SqlDbType = SqlDbType.Char,
Size = 10
};
command.Parameters.Add(parameter);
parameter = new SqlParameter
{
ParameterName = "@PetName",
Value = car.PetName,
SqlDbType = SqlDbType.Char,
Size = 10
};
command.Parameters.Add(parameter);
command.ExecuteNonQuery();
}
CloseConnection();
}
无论如何,仍然需要用字符串值交换所有@variable?
答案 0 :(得分:0)
因为参数化查询属于sql ...而另一方面是文字SQL字符串 需要时间进行编译,解析,语法检查等...