[Webinar] Streamline your web hosting managementRegister Today

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 145
  • Last Modified:

MySQL database throwing error as There is already an open DataReader associated with this Connection which must be closed first.

Hi Experts,

Am using the following code to check user login below is my code


 //suppose col0 and col1 are defined as VARCHAR in the DB
                string query = "SELECT * FROM user WHERE username = '" + TextBox1.Text + "' AND password = '" + TextBox2.Text + "'";
                var cmd = new MySqlCommand(query, dbCon.Connection);
                // cmd.ExecuteReader();
                MySqlDataReader rdr = cmd.ExecuteReader(); ;
                 var da = new MySqlDataAdapter(cmd);
                DataTable dt = new DataTable();
                da.Fill(dt);
                if (dt.Rows.Count > 0)
                {
                    Session["ValidateLogOn"] = true;
                    Session["UserName"] = Convert.ToString(dt.Rows[0]["username"]);
                    Session["UserId"] = Convert.ToString(dt.Rows[0]["ID"]);
                    Session["Email"] = Convert.ToString(dt.Rows[0]["Email"]);
                    Response.Redirect("Dashboard.aspx");
                }

Open in new window



But throwing error as
There is already an open DataReader associated with this Connection which must be closed first.
0
karthik80c
Asked:
karthik80c
  • 3
  • 2
2 Solutions
 
AndyAinscowFreelance programmer / ConsultantCommented:
Have you closed the other data reader before running this code?
0
 
karthik80cAuthor Commented:
Other Data reader means
0
 
AndyAinscowFreelance programmer / ConsultantCommented:
another DataReader, not the one you have in your code snippet
1
 
karthik80cAuthor Commented:
oh ok ANdy thanks for your Help . I think i didn't closed my Reader that's the problem . Got it Thanks Buddy. Please use Using statement to avoid this kind of problem  

using (MySqlDataReader rdr = cmd.ExecuteReader())
                {



}

Open in new window

0
 
karthik80cAuthor Commented:
Please use the using statement  or close the reader . Its best to use using statement when error occurs it automatically close the Reader

using (MySqlDataReader rdr = cmd.ExecuteReader())
                {

}
0

Featured Post

Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now