简体   繁体   English

SQLBulkCopy在失败时上传任何数据吗?

[英]Does SQLBulkCopy Upload any data upon failure?

I am doing a sql bulk copy of data from an excel spreadsheet to a temp table, and then from a temp table to a production database. 我正在从excel电子表格到临时表,然后从临时表到生产数据库进行数据的sql批量复制。

My question is this, if for any reason the upload fails either to the temp table or to the production database, does the transaction get rolled back and no data gets imported or modified existing data? 我的问题是,如果由于任何原因上传到临时表或生产数据库失败,事务是否会回滚并且没有数据被导入或修改现有数据?

By default SqlBulkCopy will roll back to the last batch you completed. 默认情况下, SqlBulkCopy将回滚到您完成的最后一批 If you have a BatchSize of 0 (the default value) it will do it all in a single batch but you may get a timeout if the batch takes too long to upload (default 30 seconds). 如果BatchSize为0(默认值),它将在一个批处理中完成所有操作,但如果批处理上载时间过长(默认为30秒),则可能会超时

Another option is wrap the entire thing in a external transaction and pass it in to the constructor . 另一种选择是将整个事物包装在外部事务中并将其传递给构造函数 This will roll back the entire insert operation on a error instead of just the last batch, this allows you to use smaller batches but still have the entire insert be a single transaction. 这将在错误而不是最后一批上回滚整个插入操作,这允许您使用较小的批次但仍然将整个插入作为单个事务。 This also lets you use that same transaction for moving data from the temporary staging table in to your live data. 这也允许您使用相同的事务将数据从临时登台表移动到您的实时数据。

Here is a snippit taken from the MSDN 这是从MSDN获取的snippit

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

    using (SqlTransaction transaction = destinationConnection.BeginTransaction())
    {
        using (SqlBulkCopy bulkCopy = new SqlBulkCopy(
                   destinationConnection, SqlBulkCopyOptions.KeepIdentity,
                   transaction))
        {
            bulkCopy.BatchSize = 10;
            bulkCopy.DestinationTableName = "dbo.BulkCopyDemoMatchingColumns";

            // Write from the source to the destination. 
            // This should fail with a duplicate key error. 
            try
            {
                bulkCopy.WriteToServer(reader);
                transaction.Commit();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                transaction.Rollback();
            }
            finally
            {
                reader.Close();
            }
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM