0

I am looking out for a help, I am trying to move data from Cosmos db to Sql db using .Net. So, in the process, I am facing issue here.

This cnnInsert.Close(), gets closed after every single insertion of record, how to avoid it from closing after each single insertion of record.

enter code here
 commInsert.Parameters.AddWithValue("@xxxx", "xxxx");
                        commInsert.Parameters.AddWithValue("xxxxx", "tobedeleted");
                        commInsert.Parameters.AddWithValue("xxxxx", xxxxxx);
                        commInsert.Parameters.AddWithValue("xxxx", "tobedeleted");
                        commInsert.Parameters.AddWithValue("xxxx", xxxxx);
                        commInsert.ExecuteNonQuery();
                        flag = true;
                        cnnInsert.Close();                        
                        Console.WriteLine("records updated for " + email);
                    }
Sai Akhil
  • 11
  • 5

1 Answers1

0

Simply, don't write this line of code: cnnInsert.Close()

But, I am of the conviction that every object should be disposed that implements IDisposable interface. You can use something like below as a best practice:

using (SqlConnection connection = new SqlConnection(connectionString))
{
   connection.Open();

   using (SqlCommand command1 = new SqlCommand(query1, connection))
   {
      // Execute command, etc. here
   }

   using (SqlCommand command2 = new SqlCommand(query2, connection))
   {
      // Execute command, etc. here
   }

   using (SqlCommand command3 = new SqlCommand(query3, connection))
   {
      // Execute command, etc. here
   }
}
Harshita Singh
  • 4,590
  • 1
  • 10
  • 13
  • Thanks for the answer, but by not using this line cnnInsert.Close() code doesnt work at all and thanks for the new practise of deifining objects, I will try it – Sai Akhil Oct 20 '20 at 11:27
  • Check out this SO question on this: https://stackoverflow.com/questions/49259804/disposing-sqlcommand – Harshita Singh Oct 20 '20 at 11:38