Eri*_*ver 18 .net c# sql sqlconnection
我经常使用看起来像这样的模式.我想知道这是否正常,或者是否有最佳实践我不在这里申请.
具体来说,我在想; 在抛出异常的情况下,我在finally块中的代码足以确保连接被正确关闭?
public class SomeDataClass : IDisposable
{
private SqlConnection _conn;
//constructors and methods
private DoSomethingWithTheSqlConnection()
{
//some code excluded for brevity
try
{
using (SqlCommand cmd = new SqlCommand(SqlQuery.CountSomething, _SqlConnection))
{
_SqlConnection.Open();
countOfSomething = Convert.ToInt32(cmd.ExecuteScalar());
}
}
finally
{
//is this the best way?
if (_SqlConnection.State == ConnectionState.Closed)
_SqlConnection.Close();
}
//some code excluded for brevity
}
public Dispose()
{
_conn.Dispose();
}
}
Run Code Online (Sandbox Code Playgroud)
Skl*_*vvz 45
将数据库处理代码包装在"使用"中
using (SqlConnection conn = new SqlConnection (...))
{
// Whatever happens in here, the connection is
// disposed of (closed) at the end.
}
Run Code Online (Sandbox Code Playgroud)
出于某种原因,.Net Framework保留了连接池.相信它!:)您不必编写如此多的代码来连接数据库并释放连接.
您可以使用'using'语句并放心'IDBConnection.Release()'将为您关闭连接.
高度精细的"解决方案"往往会导致错误的代码.简单就是更好.
MSDN Docs让这个很清楚......
您可能没有(也不想)禁用连接池,因此在您调用"关闭"后,池最终会管理连接状态.这可能很重要,因为在所有打开的连接中从数据库服务器端看可能会感到困惑.
那么为什么还要考虑关闭?只需调用Close()即可.
这就是使用块导致闭合连接的原因. 使用呼叫为您处理.
重要的安全提示.谢谢,Egon.
| 归档时间: |
|
| 查看次数: |
15514 次 |
| 最近记录: |