代码中使用连接是什么
代码中 using (connection)
的目的是什么 - 请解释一下
static void HasRows(SqlConnection connection)
{
using (connection)/// what is this line
{
SqlCommand command = new SqlCommand(
"SELECT CategoryID, CategoryName FROM Categories;",
connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
Console.WriteLine("{0}\t{1}", reader.GetInt32(0),
reader.GetString(1));
}
}
else
{
Console.WriteLine("No rows found.");
}
reader.Close();
}
}
What is the purpose of using (connection)
in the code - please explain me
static void HasRows(SqlConnection connection)
{
using (connection)/// what is this line
{
SqlCommand command = new SqlCommand(
"SELECT CategoryID, CategoryName FROM Categories;",
connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
Console.WriteLine("{0}\t{1}", reader.GetInt32(0),
reader.GetString(1));
}
}
else
{
Console.WriteLine("No rows found.");
}
reader.Close();
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
确保应用程序使用完连接后关闭连接。
类似于
Try Catch
。释放连接是关闭连接的另一种说法。打开的连接可能会泄漏内存,如果内存太多,它可能会减慢或冻结您所连接的任何内容。
即使您从所在类返回某些内容,
using
函数也会关闭连接。与try catch
相同。无论括号内发生什么,它总是关闭连接。即使存在超出类/应用程序的异常,连接仍然会关闭makes sure that
connection
is closed when the application is done using it.similar to a
Try Catch
.Disposing of the connection is another way of saying closing a connection. An open connection can leak memory and if you have too many it can slow down or freeze up whatever you are connecting to.
the
using
function closes the connection even after you return something from the class you are in. same as thetry catch
. it always closes the connection no matter what happens inside the brackets. even if there is an exception that breaks out of the class/application the connection still gets closed使用
引用自网站:
using
语句允许程序员指定使用资源的对象何时应该释放它们。提供给 using 语句的对象必须实现 IDisposable 接口。该接口提供了Dispose
方法,该方法应该释放对象的资源。Using
Quote from site:
The
using
statement allows the programmer to specify when objects that use resources should release them. The object provided to the using statement must implement theIDisposable
interface. This interface provides theDispose
method, which should release the object's resources.我可能会将该方法重写为如下所示:
在原始实现中,调用者可能位于
ObjectDisposeException
异常的接收端,因为 SqlConnection 是作为参数传入的。I would probably re-write the method to something like the following:
In your original implementation the caller could be at the receiving end of an
ObjectDisposedException
exception, because the SqlConnection is passed in as a parameter.