什么在代码中使用连接 [英] What is using connection in the code

查看:59
本文介绍了什么在代码中使用连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在代码中使用(连接)的目的是什么-请向我解释

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


推荐答案

using (connection){
    connection.Open();
}

确保连接在应用程序使用完后将其关闭。
类似于尝试捕获

makes sure that connection is closed when the application is done using it. similar to a Try Catch.

try{
    connection.Open();
}
catch{
}
finally{
    connection.Dispose(); 
}

销毁连接是关闭连接的另一种说法。开放的连接可能会泄漏内存,如果连接过多,则会减慢或冻结所连接的对象。

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.

使用函数会关闭连接,即使您从所在的类返回了某些内容也是如此。与 try catch 相同。无论括号内发生什么,它始终会关闭连接。即使存在超出类/应用程序的异常,连接仍然会关闭

the using function closes the connection even after you return something from the class you are in. same as the try 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

这篇关于什么在代码中使用连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆