gpt4 book ai didi

c# - 抛出异常时确保关闭 SQL 连接的正确方法是什么?

转载 作者:IT王子 更新时间:2023-10-29 04:45:49 29 4
gpt4 key购买 nike

我经常使用看起来像这样的模式。我想知道这是否合适,或者是否有我未在此处应用的最佳实践。

我特别想知道;在抛出异常的情况下,finally block 中的代码是否足以确保正确关闭连接?

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

最佳答案

将您的数据库处理代码包装在“using”中

using (SqlConnection conn = new SqlConnection (...))
{
// Whatever happens in here, the connection is
// disposed of (closed) at the end.
}

关于c# - 抛出异常时确保关闭 SQL 连接的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/141204/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com