ado.net Closing Connection when using “using” stat

2019-01-05 04:59发布

I am doing my database access methods to SQL Server like this

  using (SqlConnection con = new SqlConnection(//connection string)
  {
    using (SqlCommand cmd = new SqlCommand(storedProcname, con))
     {
       try{
           con.open();
           //data reader code
       }
       catch
       {

       }
     }
  }

Do I need to be closing or disposing of SqlCommand, or will the using statement take care of that for me? I just don't want connection hanging open Thanks

标签: c# tsql ado.net
7条回答
姐就是有狂的资本
2楼-- · 2019-01-05 05:28

As an aside, you can make the code more concise and readable as follows:

 using (SqlConnection con = new SqlConnection(/*connection string*/))
 using (SqlCommand cmd = new SqlCommand(storedProcname, con))
 {
    //...
 }
查看更多
淡お忘
3楼-- · 2019-01-05 05:28

As Phil said, the using clause will take care of it for you. When compiled down it wraps the connection create in a try .. finally and places the connection disposal call inside the finally.

For more information you can see the using statement article at msdn.

查看更多
爷的心禁止访问
4楼-- · 2019-01-05 05:29

Yes your code will close the connection, however that typcally means release back to the connection pool to be truely closed later.

If you execute this snippet of code, and then do an sp_who and observe that your connection is still there, that would be why.

If you absolutely need the connection truely closed (an edge case to be sure) then use the ClearAllPools static method of ths SqlConnection

查看更多
一纸荒年 Trace。
5楼-- · 2019-01-05 05:31

Using keyword will automatically close the connection for you so you don't need to worry about calling connection.close() at the end every time.

查看更多
放我归山
6楼-- · 2019-01-05 05:34

I think "using" was not required for SqlCommand. "Using" for SqlConnection would have done the job for you alone. In fact you connection is submitted to Connection pool.

查看更多
Deceive 欺骗
7楼-- · 2019-01-05 05:38

when the scope

using (SqlConnection con = new SqlConnection(//connection string) 
{
}

will over , connection will automatically be disposed by runtime. so don't worry

查看更多
登录 后发表回答