使用(SqlConnection),范围和连接池

Dew*_*oel 2 c# sql sqlconnection

我最近才了解到这种连接池机制,发现我编写的SQL连接错误.我过去常常维护一个全局SQL连接,所有SqlCommands这些连接都将执行.

所以我现在正在对现有代码进行大规模更改.有不少于260个SqlCommands引用SqlConnection我正在忙着包装的全局

using (SqlConnection sqlConnection = new SqlConnection(globally_stored_connection_string))
{
    sqlConnection.Open();
    // SqlCommand comes here
}
Run Code Online (Sandbox Code Playgroud)

我认为这仍然是我必须做的一个范式转换,这个关闭连接的业务只是在不久之后打开一个新的,信任连接池来处理开销.考虑到这一点,我现在需要决定如何SqlCommands在循环内多次调用包装.非常感谢您对以下哪些代码段的首选(当然,除此之外还有更多内容,SqlCommands但这些是用来说明问题的简单示例).

选项A:

using (SqlConnection sqlConnection = new SqlConnection(connection_string))
{
    foreach(int number in numberList)
    {
        using (SqlCommand sqlCommand = new SqlCommand("SQL code here using number from foreach loop", sqlConnection))
        {
            sqlConnection.Open();
            sqlCommand.ExecuteNonQuery();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

选项B:

foreach (int number in numberList)
{
    using (SqlConnection sqlConnection = new SqlConnection(connection_string))
    {
        sqlConnection.Open();
        using (SqlCommand sqlCommand = new SqlCommand("SQL code here using number from foreach loop", sqlConnection))
        {
            sqlCommand.ExecuteNonQuery();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

vcs*_*nes 7

我认为你缺少选项C,这对我来说最有意义:

using (SqlConnection sqlConnection = new SqlConnection(connection_string))
{
    sqlConnection.Open();
    using (SqlCommand sqlCommand = new SqlCommand("SQL code here using number from foreach loop", sqlConnection))
    {
        foreach (int number in numberList)
        {
            //Modify command parameters if needed
            sqlCommand.ExecuteNonQuery();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这对执行命令的开销最小.构造一个SqlCommand对象并不是昂贵,但它也不是免费的.如果可能,我们可以在这里重复使用它.