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

后端 未结 12 2276
情话喂你
情话喂你 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:00

    In order for it to be disposed easily i use the following coding-template :

    `using (SqlConnection connection = new SqlConnection("your connection string"))
            {
                connection.Open();
                using (SqlCommand cmd = connection.CreateCommand())
                {
                    cmd.CommandText = "Select * from SomeTable";
                    using (SqlDataReader reader = cmd.ExecuteReader())
                    {
    
                        if(reader.HasRows)
                        { 
                           while(reader.Read()){
                           // assuming that we've a 1-column(Id) table 
                           int id = int.Parse(reader[0].ToString()); 
    
                           }
                        }
                    }
                } 
                connection.Close()
            }`
    

提交回复
热议问题