2012-11-12 94 views
0

我有我支持老应用程序,我遇到以下共享的SQLConnection跑:共享连接VS个人

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

现在这个连接被打开,它需要关闭每次,但它仍然得到了散发性错误,我相信这是因为它被用户共享(静态)。我的假设是否正确?我相信在每个需要它的方法中创建一个新的连接会更好,而不是每个类都有一个。或者我可以只提取静态选项,并保持每页一个连接,而不必担心跨用户污染?

感谢

回答

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。这样资源即使在发生异常时也会被释放。

+0

是一个使用需要时,尝试与最后关闭连接? – Limey

+0

'using'语句被实现为'try-finally'语句并为您关闭连接!即它在finally部分调用Dispose(),然后关闭连接。在任何情况下都会发生这种情况,即使您将using语句与“return”分开也是如此。如果你需要一个try-statement用于错误处理,并且正在用'finally'部分关闭连接,因为不需要额外的'using'。 –

1

static肯定可以使不好的事情发生,如果你试图在同一时间执行两个查询。

创建的每个地方,你使用它,Dispose在年底将是我最好的架构方法,一个新的连接。我还会用工厂方法封装SqlConnection的创建。

3

摆脱两者并宣布&定义它们,当你需要他们。

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

this answer一读。

0

先生我担心在调用execute函数之前应该启动连接,并且在执行后立即关闭,无论结果是否失败。如果您在合适的时间关闭和处理分配的资源,则无论是否为静态都无关紧要。启动连接的最佳模式是以下代码:

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(); 
} 

希望它有帮助。

干杯

+0

为什么选择投票?哪里不对? – Rikki

+0

不确定为什么某个人下了评分,但ClearPool应该完成吗?难道我不应该让连接池独自一人,让它自己处理? – Limey

+0

我没有downvote,但在finally部分中调用Dispose()会在关闭连接时执行所有必须完成的操作。 –