My code:
SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString);
SqlCommand cmd = new SqlCommand();
//..........
cmd.CommandText = "SELECT * FROM TempQn WHERE creatorId= '" +
Session["administratorID"].ToString() + "'";
dr = cmd.ExecuteReader();
while (dr.Read())
{
int ids = Int32.Parse(dr["QuestionID"].ToString());
cmd.CommandText = " INSERT INTO Answers (QuestionId,Answer) Select c.QnId, c.Answer From TempAns c Where c.Id = " + ids + " ";
cmd.ExecuteNonQuery(); //this line
}
dr.Close();
The error is:
There is already an open DataReader associated with this Command which must be closed first.
What kind of command should replace the cmd.ExecuteNonQuery();?
You can’t execute any further SQL statements as long as the DataReader is “active”.
To overcome this, store list of the SQL statements then exeucute them after reading:
Your current code is vulnerable to SQL injection attacks though and isn’t good practice – you better use Parameter instead of injecting value to the raw SQL – here is how to achieve that: