【发布时间】:2013-12-10 22:58:14
【问题描述】:
我想问一下使用数据库连接和关闭它们的常用方法是什么。
这是我的程序,但我在异常中看到,connection.Close() 不会执行。
我应该对整个块使用 try-catch 吗?因为出于某种原因,我看到大多数人没有。
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
using (SqlCommand command = new SqlCommand())
{
command.CommandText = "procedure";
command.Connection = connection;
command.CommandType = CommandType.StoredProcedure;
tmpParameter = DBUtils.createInSQLParam("@ImageID", SqlDbType.SmallInt, htmlImageId);
command.Parameters.Add(tmpParameter);
command.Connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
htmlImageDetails = GetHtmlImageDetailsFromReader(reader, true, out newId);
reader.Close();
}
connection.Close();
return htmlImageDetails;
}
}
【问题讨论】:
-
你看到了什么异常?
-
这似乎回答了你的问题 - stackoverflow.com/a/4717802/978528.
-
使用“使用”时不需要关闭,连接/阅读器会自动关闭。 .net 默认使用连接池,因此如果您将其丢弃,连接不会关闭,它会被放入池中以供重用(这在大多数情况下会提高性能)。
-
在 using 块中,对象是只读的,不能修改或重新分配。所以,也许当你 close() 被认为是对对象的修改时,因为 close() 在 using 块的关闭 } 之后是隐式的,因此会出现错误。
-
只是为了澄清@Petoj 所说的在您调用
Close()时连接没有关闭,它只是将连接返回到池,直到超时然后真正关闭。 (除非您在创建连接时告诉它不要在连接字符串中使用连接池)
标签: c# sqlconnection