原贴:http://community.csdn.net/Expert/topic/5300/5300996.xml?temp=.8228571我一般都是用:
public static SqlDataReader SqlReader(string Sql)
{
SqlConnection con=new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["ConnectionString"]);
SqlCommand cmd=new SqlCommand(Sql,con);
con.Open();
SqlDataReader resual=cmd.ExecuteReader(CommandBehavior.CloseConnection);
return resual;
}
public static DataSet SqlDS(string Sql) 
{
SqlConnection con=new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["ConnectionString"]);
SqlDataAdapter sda=new SqlDataAdapter();
sda.SelectCommand=new SqlCommand(Sql,con);
DataSet ds=new DataSet();
sda.Fill(ds,"binds");
return ds;
}
大家都说我没有关闭,但这都是我在网上看别人的样式做的
都说SqlDataAdapter会自动关闭CommandBehavior.CloseConnection
也会自动关闭CSDN朋友提示用
try
{SqlDataAdapter sda=new SqlDataAdapter();
sda.SelectCommand=new SqlCommand(Sql,con);
DataSet ds=new DataSet();
sda.Fill(ds,"binds");
return ds;}
finally
{
  con.close();
}
但我不明白的是 那里不是已经return ds 了吗,不是退出了吗
那他还会去执行con.close()吗另有CSDN朋友:
SqlDataAdapter不需要close
最好使用
using(SqlConnection conn=new SqlConnection(str))
{
}
这里他用using(SqlConnection conn=new SqlConnection(str))
有什么样的好处
谢谢大家

解决方案 »

  1.   

    try
    {SqlDataAdapter sda=new SqlDataAdapter();
    sda.SelectCommand=new SqlCommand(Sql,con);
    DataSet ds=new DataSet();
    sda.Fill(ds,"binds");
    return ds;}
    finally
    {
      con.close();
    ///这里是肯定要执行的
    }
    但我不明白的是 那里不是已经return ds 了吗,不是退出了吗
    那他还会去执行con.close()吗另有CSDN朋友:
    SqlDataAdapter不需要close
    最好使用
    using(SqlConnection conn=new SqlConnection(str))
    {
    }//到这里conn自动关闭
      

  2.   

    推荐用:
    try{
    }
    catch()
    {
    }
    finally
    {
      con.close();
    }因为如果是正常情况下你以cmd.ExecuteReader(CommandBehavior.CloseConnection);
    这样的方式可以关闭CON,但是如果出现异常那你的CON就无法关闭了。
    但是finally不同,因为try的原因,所以即使出现异常也会走完finally ,这样即使出现异常也不会出现con没有关闭的现象,或者你在catch()中来关闭con也一样。
      

  3.   

    catch 和 finally 一起使用的常见方式是:在 try 块中获取并使用资源,在 catch 块中处理异常情况,并在 finally 块中释放资源。
      

  4.   

    public static SqlDataReader SqlReader(string Sql)
    {
      using(SqlConnection conn=new SqlConnection(str))
      {
        con.Open();
        SqlDataReader resual=cmd.ExecuteReader(CommandBehavior.CloseConnection);
        return resual;
      }
    }
    是不是改成这样的样子就行了
    谢谢
      

  5.   

    using 语句允许程序员指定使用资源的对象应当何时释放资源。为 using 语句提供的对象必须实现 IDisposable 接口。此接口提供了 Dispose 方法,该方法将释放此对象的资源。
      

  6.   

    SqlDataReader resual=cmd.ExecuteReader(CommandBehavior.CloseConnection);
    return resual;
    =========
    这样是可以的,但记住要关闭reader.
      

  7.   

    哦知道了,可能是我没有关闭
    datareader谢谢大家以后我就用
    推荐用:
    try{
    }
    catch()
    {
    }
    finally
    {
      con.close();
    }
    和reade.close()谢谢结贴
      

  8.   

    Click the link to solve your problem.Good luck!