public static int ExecuteSql(string SQLString)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand(SQLString,connection))
{
try
{
connection.Open();
int rows=cmd.ExecuteNonQuery();
return rows;
}
catch(System.Data.SqlClient.SqlException E)
{
connection.Close();
throw new Exception(E.Message);
}
}
}
}

有朋友说这个方法会出现connection不关闭,我应用的时候没有这样的现象出现.这个方法真有的错吗?
还有
using (SqlConnection connection = new SqlConnection(connectionString))
{}
起到了什么作用.
希望朋友指点

解决方案 »

  1.   

    using语句,定义一个范围,在范围结束时处理对象。
    场景:
    当在某个代码段中使用了类的实例,而希望无论因为什么原因,只要离开了这个代码段就自动调用这个类实例的Dispose。
    要达到这样的目的,用try...catch来捕捉异常也是可以的,但用using也很方便。
    批这是我在网上找到的.结果,disponse还不能使coennction.close()?
      

  2.   

    ..要用using定义.好像对象是必须继承IDisposable.在结束时.自动会disponse掉.我也是新手.如果说错.请见谅.
      

  3.   

    http://topic.csdn.net/t/20050327/20/3885808.html
    的结果....
      

  4.   

    using(SqlConnection connection =  new SqlConnection(connectionString)){}   相当于try{} catch{} finally{}语句块,这样做的好处是我们取的连接对象来自于连接池,可以不用显示关闭连接,应用程序结束后自动将连接放到连接池中。 
      

  5.   

    using   (SqlConnection   connection   =   new   SqlConnection(connectionString)) 
    {} 
    当程序执行出了using域也就是出了大括号。连接会自动关闭。也可以写成
    try
    {
         SqlConnection connection = new SqlConnection(....);
    }
    catch
    {
    }
    finally
    {
    connection.close();
    }