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);
                    }

1 Answer 1

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
   }
}
Sign up to request clarification or add additional context in comments.

2 Comments

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.