0

我有一个支持的旧应用程序,并且遇到了以下共享 SQLConnection:

    private static SqlConnection cnSQL = new SqlConnection(ConfigurationManager.ConnectionStrings["SQL"].ConnectionString.ToString());
    private static SqlCommand cmdSQL = new SqlCommand();

现在,每次需要时都会打开和关闭此连接,但它仍然会出现零星错误,我相信这是因为它在用户之间共享(静态)。我的假设正确吗?我相信我最好在每个需要它的方法中创建一个新连接,而不是每个类都有一个。或者我可以删除静态选项,每页保持一个连接,而不必担心交叉用户污染?

谢谢

4

4 回答 4

3

摆脱两者并在需要时声明和定义它们。

using (var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["SQL"].ConnectionString.ToString()))
{
    using (var cmd = conn.CreateCommand())
    { ... }
}

阅读此答案

于 2012-11-12T17:51:19.430 回答
1

如果您尝试同时执行两个查询,那static肯定会发生坏事。

在您使用它的每种方法中创建一个新连接,Dispose最后将是我更喜欢的架构。我还将封装SqlConnection在工厂方法中的创建。

于 2012-11-12T17:51:03.190 回答
1

静态成员在应用程序的实际实例中的代码的所有对象和方法之间共享,但在不同用户之间绝不会共享。

我会将连接字符串设为静态,但不会将连接本身设为静态。如您所说,在每种方法中打开一个新连接。连接池将确保物理连接保持打开状态。

public static readonly string ConnectionString connString =
    ConfigurationManager.ConnectionStrings["SQL"].ConnectionString.ToString();

...

private void SomeMethod()
{
    using (var conn = new SqlConnection(connString)) {
        string sql = "SELECT ...";
        using (var cmd = new SqlCommand(sql, conn)) {
            ...
        }
    }
}

确保将代码嵌入到using-statements 中。这样即使发生异常也会释放资源。

于 2012-11-12T17:51:33.703 回答
0

先生,恐怕必须在您调用执行函数之前启动连接,并在执行后立即关闭,无论结果是否失败。如果您在正确的时间关闭并处置分配的资源,是否保持静态都没有区别。启动连接的最佳模式是以下代码:

SqlCommand command = new SqlConnection("[The connection String goes here]").CreateCommand();

try
{
    command.Parameters.Add(new SqlParameter() { ParameterName = "ParameterA", Direction = ParameterDirection.Input, Value = "Some value" });

    command.Parameters.Add(new SqlParameter() { ParameterName = "ReturnValue", Direction = ParameterDirection.ReturnValue });

    command.CommandText = "[YourSchema].[YourProcedureName]";

    command.CommandType = CommandType.StoredProcedure;

    command.Connection.Open();

    command.ExecuteNonQuery();
}
catch (Exception ex)
{
    //TODO: Log the exception and return the relevant result.
}
finally
{
    if (command.Connection.State != ConnectionState.Closed)

        command.Connection.Close();

    SqlConnection.ClearPool(command.Connection);

    command.Connection.Dispose();

    command.Dispose();
}

希望能帮助到你。

干杯

于 2012-11-12T18:26:18.337 回答