我想问一下使用数据库连接的常见方式和关闭它们的方法。
这是我的程序,但我在异常中看到连接.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;
}
}
Close()
时,连接并没有关闭,它只是将连接返回到池中直到超时,然后才会真正关闭。(除非在创建连接时在连接字符串中告诉它不使用连接池) - Scott Chamberlain