1

1 つのメソッドで OpenConnection() を 2 回呼び出すことができないのはなぜですか? 呼び出すと、次のエラーが表示されます。

接続はすでに開いています。

SelectDisPatient()とで 2 回呼び出します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()メソッドを削除すると、接続を閉じる必要があると表示されます。

4

1 に答える 1

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();

    }
 }
于 2013-04-10T16:35:14.257 に答える