Inserting Data to Sql Db from Cosmos Db

114 Views Asked by At

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

There are 1 best solutions below

2
On

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