![](/img/trans.png)
[英]What will it be if SqlConnection.Close() or SqlConnection.Dispose() is not called?
[英]SqlConnection.Close() inside using statement
我正在使用此代码:
public void InsertMember(Member member)
{
string INSERT = "INSERT INTO Members (Name, Surname, EntryDate) VALUES (@Name, @Surname, @EntryDate)";
using (sqlConnection = new SqlConnection(sqlConnectionString_WORK))
{
sqlConnection.Open();
using (SqlCommand sqlCommand = new SqlCommand(INSERT, sqlConnection))
{
sqlCommand.Parameters.Add("@Name", SqlDbType.VarChar).Value = member.Name;
sqlCommand.Parameters.Add("@Surname", SqlDbType.VarChar).Value = member.Surname;
sqlCommand.Parameters.Add("@EntryDate", SqlDbType.Date).Value = member.EntryDate;
sqlCommand.ExecuteNonQuery();
}
}
}
不加sqlConnection.Close();
有错吗sqlConnection.Close();
在处理之前? 我的意思是。 它没有显示任何错误,根本没有问题。 最好先关闭它吗? 如果是,为什么?
无需Close or Dispose
using
块将为您处理。
正如MSDN 所述:
下面的示例创建一个 SqlConnection,打开它,显示它的一些属性。 连接在 using 块结束时自动关闭。
private static void OpenSqlConnection(string connectionString)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
Console.WriteLine("ServerVersion: {0}", connection.ServerVersion);
Console.WriteLine("State: {0}", connection.State);
}
}
using statement ensures that Dispose is called
即使在您调用对象的方法时发生异常。 You can achieve the same result by putting the object inside a try block and then calling Dispose in a finally block
; 事实上,这就是编译器如何翻译using 语句。 MSDN
所以最终你的代码行
using (sqlConnection = new SqlConnection(sqlConnectionString_WORK))
将被编译器IDisposable object in the finally
调用IDisposable object in the finally
转换为普通的try finally block
您必须通过调用Close或Dispose显式关闭连接。 Close和Dispose在功能上是等效的。
因此,调用Dispose
(隐式如此,甚至使用using
)将覆盖您的基础,就像它一样。
同样值得注意的是,我认为,虽然不是特定于您的情况,但是当事物包含在using
语句中时,始终会有效地调用Close
- 如果省略它并且在没有适当的情况下发生异常,则情况可能并非如此try
/ catch
/ finally
处理。
不加sqlConnection.Close()有错吗? 在处理它之前
不,只要您在Using
中使用连接即可。 当您离开 using 作用域时,将调用Dispose
进行 sql 连接。 这将关闭现有连接并释放所有资源。
using 语句是一个 try finally 块,在您的情况下,最后一个块将有一个connection.Dispose()
调用。 所以你真的不需要一个独立的connection.Close()
语句。
优点是即使在发生异常的情况下也能确保处理,因为 finally 块将始终运行。
try
{
sqlConnection.Open();
// ....
}
finally
{
if(sqlConnection != null)
sqlConnection.Dispose();
}
不,没有错。 sqlConnection 在通过using块并调用 Dispose 方法后将关闭连接。 SqlConnection.Dispose() 等于 SqlConnection.Close() 方法。
来自 MSDN:如果 SqlConnection 超出范围,它不会被关闭。 因此,您必须通过调用 Close 或 Dispose 显式关闭连接。 Close 和 Dispose 在功能上是等效的。
您正在使用Using
,它将为您Dispose()
对象。
如果您将连接置于Using
语句之外,那么是的 - 您需要在完成后关闭连接。
这是一个非常有趣的问题,并不像许多人想象的那么明显。 仅当将处置使用该连接的所有对象时,using语句才能正确用于连接。 前段时间我们在sql server中打开连接时出现问题。 一切看起来很好,因为连接在内部使用语句,但其中一个开发人员使用SqlDataReader创建了几个方法,并没有正确关闭它。 因为那个连接没有被释放。
这样做的原因是垃圾收集器的工作方式。 长话短说 - 它创建了一个对象的地图,当没有对这些对象的活动引用时,这些对象要处理并实际处理它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.