简体   繁体   中英

Webservice+consumer c# error Server was unable to process request. ---> The connection is already open

i have a webservice and a comsumer, the webservice has its methode where it returns data from a mysql database. in the comsumer i called

WebService.Service1 Service = new WebService.Service1();        

in the beginning (not within a methode) when the consumer starts asking for data it will be 20 requests within 10 minutes first 15-18 requests worked perfectly but the last few times it returns the error

Server was unable to process request. ---> The connection is already open.

I hope i provided enough information like this, i rather not post the code.

This is the methode of the webservice:

        public string GetAnswer(string Question, string Option1, string Option2, string Option3, string Option4)
    {
        string connstring = "Server=Server;Port=3306;Database=DB;UID=User;password=pw;";
        MySqlConnection conn = new MySqlConnection(connstring);
        MySqlCommand command = conn.CreateCommand();

        command.CommandText = "SELECT * FROM `tbl` where `Question` = '" + Question + "' LIMIT 1";
        conn.Open();

        MySqlDataReader reader = command.ExecuteReader();
        if (reader.HasRows)
        {
            string TheAnswer = "";
            while (reader.Read())
            {
                string question = reader["Question"].ToString();
                string answer = reader["Answer"].ToString();
                if (Option1.Equals(answer))
                    TheAnswer = Option1;
                if (Option2.Equals(answer))
                    TheAnswer = Option2;
                if (Option3.Equals(answer))
                    TheAnswer = Option3;
                if (Option4.Equals(answer))
                    TheAnswer = Option4;
            }
            conn.Close();
            conn.Dispose();
            return TheAnswer;
        }
        else
        {
            MySqlCommand command2 = conn.CreateCommand();
            command.CommandText = "Insert Into `new` (`Question`, `Answer1`,`Answer2`,`Answer3`,`Answer4`) VALUES ('" + Question + "','" + Option1 + "','" + Option2 + "','" + Option3 + "', '" + Option4.Replace("~", " ") + "')";
            conn.Open();
            command.ExecuteNonQuery();

            conn.Close();
            conn.Dispose();
            return "Error: Question is unknown, saving the question to get it answered.";
        }
    }

You have conn.open() in your else statement, and the connection was already opened before that. You should probably consider using the using statement:

using (MySqlConnection conn = new MySqlConnection(connstring))
{
  using (MySqlCommand command2 = conn.CreateCommand())
  {
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM