这个类定义有什么问题?

时间:2011-08-06 15:58:08

标签: c#

我有一个这样的课程:

class connect:IDisposable
{
   public void OpenChannel(SqlConnection ch)
   {
     ch.ConnectionString=".....";
     ch.Open();
   }
   public void Dispose()
  {
  }
}

还有另外一个类:

public Cust
{
   SqlConnection channel=new SqlConnection();
   SqlCommand command=new SqlCommand();

   public void Method()
   {
       using(connect con=new connect())
         {
         con.OpenChannel(channel);
         command.connection=channel;
         .....
         ....
         ....
         command.ExecuteNonQuery();
         }
   }

但是当我运行ExcuteNotQuery()时出现错误:“没有打开连接” 那有什么不对?

1 个答案:

答案 0 :(得分:3)

public Cust
{
   SqlConnection channel=new SqlConnection();
   SqlCommand command;//=new SqlCommand();

   public void Method()
   {
       using(connect con=new connect())
         {
         con.OpenChannel(channel);
         //command.connection=channel;

         // create command from open connection
         command = channel.CreateCommand();
         .....
         ....
         ....
         command.ExecuteNonQuery();
         }
   }