error 'there is already an open datareader associated with this command which must be closed first'

后端 未结 12 2290
情话喂你
情话喂你 2020-12-05 10:15

runtime error \'there is already an open datareader associated with this command which must be closed first\'

objCommand = new SqlCommand(\"SELECT field1, fi         


        
12条回答
  •  情话喂你
    2020-12-05 11:09

    What version of SQL Server are you using? The problem might be with this:

    (from http://msdn.microsoft.com/en-us/library/9kcbe65k.aspx)

    When you use versions of SQL Server before SQL Server 2005, while the SqlDataReader is being used, the associated SqlConnection is busy serving the SqlDataReader. While in this state, no other operations can be performed on the SqlConnection other than closing it. This is the case until the Close method of the SqlDataReader is called.

    So, if this is what's causing your problem, you should first read all the data, then close the SqlDataReader, and only after that execute your inserts.

    Something like:

    objCommand = new SqlCommand("SELECT field1, field2 FROM sourcetable", objConn);
    
    objDataReader = objCommand.ExecuteReader();
    
    List values = new List();
    while (objDataReader.Read())
    {
        values.Add(objDataReader[0]);
    }
    
    objDataReader.Close();
    
    foreach (object value in values)
    {
        objInsertCommand = new SqlCommand("INSERT INTO tablename (field1, field2) VALUES (3, '" + value + "')", objConn);
        objInsertCommand.ExecuteNonQuery();
    }
    
        

    提交回复
    热议问题