【问题标题】:Inserting Data to Sql Db from Cosmos Db从 Cosmos Db 向 Sql Db 插入数据
【发布时间】:2026-01-21 14:30:02
【问题描述】:

我正在寻求帮助,我正在尝试使用 .Net 将数据从 Cosmos db 移动到 Sql db。所以,在这个过程中,我在这里遇到了问题。

这个cnnInsert.Close(),每次插入记录后都会关闭,如何避免每次插入记录后关闭。

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

【问题讨论】:

    标签: .net azure-cosmosdb sqldb


    【解决方案1】:

    简单地说,不要写这行代码:cnnInsert.Close()

    但是,我坚信应该处理每个实现IDisposable 接口的对象。您可以使用以下内容作为最佳实践:

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

    【讨论】: