如果有如下的方法: 
       public static DataSet GetInfo()
        {
            DataSet ds = new DataSet();
            string sqlCode = @"Select xx From Table Where xx";
            string connectionString = "xxxxxxxxxxxxxxxxx";            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                SqlCommand cmd = new SqlCommand(sqlCode, conn);
                cmd.CommandTimeout = 0;
                SqlDataAdapter adapter = new SqlDataAdapter(cmd);
                adapter.Fill(ds);                if (ds != null && ds.Tables.Count > 0)
                    return ds;
                else
                    return null;
            }
        }
在使用SqlDataAdapter时,不必像SqlDataReader那样需要显示的指定 SqlConnection为Open状态,请问,在用SqlDataAdapter时,数据库连接会打开吗?
如果我加上 conn.Open() 和 conn.Close(),效率会比上面的代码要低吗?加和不加有什么区别?

解决方案 »

  1.   

    这种写法不需要加conn.Open()和conn.Close()的,用SqlDataAdapter中命令执行的时候会自动打开数据库连接的,当数据填充完毕会自动释放连接资源的。
      

  2.   

    学习   对.net 了解不是很深  我自己的常规写法 都是  
    try
    {SqlConnection conn = new SqlConnection(connectionString);                SqlCommand cmd = new SqlCommand(sqlCode, conn);
                    cmd.CommandTimeout = 0;
                    SqlDataAdapter adapter = new SqlDataAdapter(cmd);
                    adapter.Fill(ds);

    catch
    {
    throw;
    }
    fanily
    {
     if(conn的状态 是否打开  )  如果打开  关闭 
    }我不知道我这样写和他那样在效率上有多大的差别
      

  3.   

    用了using的话 不用写数据库的打开和关闭
    它会自动处理
    不用using的话就要加上了
      

  4.   

    但是用using的自动打开数据库连接 和 显式的指定 SqlConnection.Open()有什么区别呢?
    我在using块里面用SqlDataReader的话,还是需要显式指定 SqlConnection.Open(),不然就会报错。
      

  5.   

    在使用SqlDataAdapter时,不必像SqlDataReader那样需要显示的指定 SqlConnection为Open状态, 
    请问,在用SqlDataAdapter时,数据库连接会打开吗? 
    如果我加上 conn.Open() 和 conn.Close(),效率会比上面的代码要低吗?加和不加有什么区别? 
    ---
    首先说说using的使用
      他的作用是确保实现了IDispose接口的对象在出块以后自动释放资源,就相当于自动SqlConnection.close()
      但是还得open(),可以任务这是托管型代码的一个特点,使用垃圾收集器---
    接着说说SqlDataAdapter
    使用他时不用自己手动打开和关闭连接,他有四个属性,对应四种操作,select insert update delete
    我们可以为这个四个属性添加响应的操作,以完成批量插入,更新,删除
      

  6.   

    意思就是说,不管你是否使用using,在不使用adapter的情况下,是必须显示打开连接的
    用了using可以不些close(),但良好的习惯是写
      

  7.   

    使用using时代码执行完,就自动进行资源回收释放了,
    一般用来释放数据库连接资源。
    当然conn.Open() 和 conn.Close()手写也是可以的
      

  8.   

    能自动的就自动,又想自动又想手动挺麻烦的,如果要手动的话必须
    if(conn.state==connectionstate.open) conn.close();
    否则可能会出错.