在多次执行相同的SQL查询时重用SqlCommand更好吗?

Ars*_*nko 14 c# refactoring readability

使用相同的查询但不同的参数查询数据库时,最好是:

  • 一次性使用,
  • 或者创建两个单独的查询?

使用单个示例:

using (SqlCommand addProduct = new SqlCommand(@"insert into [Products].[Products] ([Name], [Price]) values (@name, @price)", sqlConnection))
{
    // Insert the first product.
    addProduct.Parameters.AddWithValue("@name", "Product 1");
    addProduct.Parameters.AddWithValue("@price", 41F);
    int countAffectedRows = addProduct.ExecuteNonQuery();
    Debug.Assert(countAffectedRows == 1, "Wrong number of rows affected.");

    addProduct.Parameters.Clear();

    // Insert the second product.
    addProduct.Parameters.AddWithValue("@name", "Product 2");
    addProduct.Parameters.AddWithValue("@price", 49.9);
    countAffectedRows = addProduct.ExecuteNonQuery();
    Debug.Assert(countAffectedRows == 1, "Wrong number of rows affected.");
}
Run Code Online (Sandbox Code Playgroud)

使用两个单独查询的相同代码示例:

// Insert the first product.
using (SqlCommand addProduct = new SqlCommand(@"insert into [Products].[Products] ([Name], [Price]) values (@name, @price)", sqlConnection))
{
    addProduct.Parameters.AddWithValue("@name", "Product 1");
    addProduct.Parameters.AddWithValue("@price", 41F);
    int countAffectedRows = addProduct.ExecuteNonQuery();
    Debug.Assert(countAffectedRows == 1, "Wrong number of rows affected.");
}

// Insert the second product.
using (SqlCommand addProduct = new SqlCommand(@"insert into [Products].[Products] ([Name], [Price]) values (@name, @price)", sqlConnection))
{
    addProduct.Parameters.AddWithValue("@name", "Product 2");
    addProduct.Parameters.AddWithValue("@price", 49.9);
    int countAffectedRows = addProduct.ExecuteNonQuery();
    Debug.Assert(countAffectedRows == 1, "Wrong number of rows affected.");
}
Run Code Online (Sandbox Code Playgroud)

在我看来,第二个必须是首选,因为:

  • 它可以更清楚地看到SQL命令的位置和执行的次数,
  • 如果将来出于某种原因必须在一种情况下修改查询,而在另一种情况下不能修改查询,则更容易修改,
  • 第一个让人很容易忘记SqlCommand.Parameters.Clear().

另一方面,第一个示例更清楚地表明在两种情况下查询都相同,并且只有参数发生变化.

Joe*_*ite 17

除非您计划调用Prepare,否则重用命令实例几乎没有什么好处.

如果你要多次运行该命令(几十次或更多),那么你可能想要创建命令,准备它,在循环中执行它,然后处理它.如果您多次运行该命令,性能提升非常重要.(在准备之前,您可以添加一次参数 - 不要像在第一个代码示例中那样每次删除和重新添加它们.您应该每次都更改参数,而不是创建新参数. )

如果你只是在几次运行命令,性能不是问题,你应该选择你喜欢的任何一种风格.每次创建命令都有一个好处,即很容易将其提取到方法中,因此您不必重复自己.