为什么OpenConnection()不能在一个方法中被调用两次?

时间:2013-04-10 16:27:17

标签: c# mysql database-connection

为什么我不能在一个方法中两次调用OpenConnection()?当我调用它时会出现此错误:

  

连接已经打开。

我在SelectDisPatient()Count()中称呼它两次。请参阅for (int index = 0; index < Count(); index++)

上的代码

此方法SelectDisPatient

public void SelectDisPatient(FrmVIRGO frm)
{
   string query = "SELECT id_pasien FROM tb_patient_information ";
   if (this.OpenConnection() == true)
   { //Create Command
      MySqlCommand cmd = new MySqlCommand(query, connection);
      //Create a data reader and Execute the command
      MySqlDataReader dataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
      if (dataReader.HasRows)
      {
         for (int index = 0; index < Count(); index++)
         dataReader.Read();
         frm.tbName.Text = dataReader[0].ToString(); 
      } 
         //close Data Reader
         dataReader.Close();

         //close Connection
         this.CloseConnection();

    }
 }

这个Count()方法:

public int Count()
{
   string query = "SELECT Count(*) FROM tb_patient_information";
   int Count = -1;

   //Open Connection
   if (this.OpenConnection() == true)
   {
      //Create Mysql Command
      MySqlCommand cmd = new MySqlCommand(query, connection);

      //ExecuteScalar will return one value
      Count = int.Parse(cmd.ExecuteScalar()+"");

      //close Connection
      this.CloseConnection();

      return Count;
    }
    else
    {
       return Count;
    }
 }

但是当我在(this.OpenConnection() == true)方法中移除Count()时,我说我需要关闭连接。

1 个答案:

答案 0 :(得分:2)

尝试:

public void SelectDisPatient(FrmVIRGO frm)
{
   int count =  Count();
   string query = "SELECT id_pasien FROM tb_patient_information ";
   if (this.OpenConnection() == true)
   { //Create Command
      MySqlCommand cmd = new MySqlCommand(query, connection);
      //Create a data reader and Execute the command
      MySqlDataReader dataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
      if (dataReader.HasRows)
      {
         for (int index = 0; index < count ; index++)
         dataReader.Read();
         frm.tbName.Text = dataReader[0].ToString(); 
      } 
      //close Data Reader
      dataReader.Close();

      //close Connection
      this.CloseConnection();

    }
 }