我有一个web服务和一个comsumer,webservice有它的方法,它从mysql数据库返回数据。 在comsumer我打电话给
WebService.Service1 Service = new WebService.Service1();
开头的(不在方法中) 当消费者开始询问数据时,将在10分钟内提出20个请求,首先15-18个请求工作正常,但最后几次返回错误
服务器无法处理请求。 --->已经连接了 开。
我希望我提供了这样的足够信息,我宁愿不发布代码。
这是网络服务的方法:
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.";
}
}
答案 0 :(得分:2)
你的else语句中有conn.open()
,之前连接已经打开。您应该考虑使用using
语句:
using (MySqlConnection conn = new MySqlConnection(connstring))
{
using (MySqlCommand command2 = conn.CreateCommand())
{
}
}