1

Problems: 1: The Read method cannot be called when another read operation is pending. 2: There is already an open DataReader associated with this Connection which must be closed first.

I have used Asp.net c# and MySql to develop my project. When I did publish it, I faced a problem. The problem is when more than one user open the website, the MySql connection stop working. There is a sample of my code.

 public partial class ConTest : System.Web.UI.Page
    {
   MySqlConnection con = new MySqlConnection("Server= mysql-85112-0.cloudclusters.net; port=11923; Database=Test; Uid=xxxx; Pwd=xxxx;");
        MySqlCommand cmd = new MySqlCommand();
        MySqlDataReader dr;
        protected void Page_Load(object sender, EventArgs e)
        {

            cmd.Connection = con;

            Database.con.Close();
            Database.con.Open();
            cmd.CommandText = "select s_name from students_info";
            dr = cmd.ExecuteReader();
            while (dr.Read())
            {
                Label1.Text = dr[0].ToString();
            }
            Database.con.Close();


        }
    }
2

1 Answer 1

0

Don't share MySqlConnection objects. Create a new one when you need it, and close it automatically by using a using declaration:

protected void Page_Load(object sender, EventArgs e)
{
    using var connection = new MySqlConnection("Server= mysql-85112-0.cloudclusters.net; port=11923; Database=Test; Uid=xxxx; Pwd=xxxx;");
    using var command = new MySqlCommand("select s_name from students_info", connection);

    connection.Open();
    using var dr = command.ExecuteReader();
    if (dr.Read())
    {
        Label1.Text = dr.GetString(0);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.