如何在bulkCopy.WriteToServer之后返回结果

111*_*110 4 c# sql-server sqlbulkcopy sql-server-2008

根据接受的答案更新:

bool success = false;
using (var bulkCopy = new SqlBulkCopy(connection)) //using!
{
    connection.Open();

    //explicit isolation level is best-practice
    using (var tran = connection.BeginTransaction(IsolationLevel.ReadCommitted))
    {
        bulkCopy.DestinationTableName = "table";
        bulkCopy.ColumnMappings...

        using (var dataReader = new ObjectDataReader<SomeObject>(paths))
        {            
            bulkCopy.WriteToServer(dataReader);
            success = true;
        }

        tran.Commit(); //commit, will not be called if exception escapes
    }
}
return success;
Run Code Online (Sandbox Code Playgroud)

我使用BulkCopy类来进行大插入,效果很好。
执行WriteToServer并将数据保存到数据库后
,我不想知道所有数据是否已成功保存,以便我可以返回,true/false因为我需要保存全部或不保存?

    var bulkCopy = new SqlBulkCopy(connection);

    bulkCopy.DestinationTableName = "table";

    bulkCopy.ColumnMappings...

    using (var dataReader = new ObjectDataReader<SomeObject>(paths))
    {
        try
        {
        bulkCopy.WriteToServer(dataReader);
        }
        catch(Exception ex){ ... }    
}
Run Code Online (Sandbox Code Playgroud)

usr*_*usr 5

如果调用WriteToServer无异常地完成,则所有行都将被保存并存储在磁盘上。这只是 SQL Server DML 的标准语义。批量复制没什么特别的。

与所有其他 DML 一样,SqlBulkCopy它也是全有或全无的。除非您配置了未配置的批量大小。

using (var bulkCopy = new SqlBulkCopy(connection)) //using!
{
    connection.Open();

    //explicit isolation level is best-practice
    using (var tran = connection.BeginTransaction(IsolationLevel.ReadCommitted))
    {
        bulkCopy.DestinationTableName = "table";
        bulkCopy.ColumnMappings...

        using (var dataReader = new ObjectDataReader<SomeObject>(paths))
        {
            //try
            //{
            bulkCopy.WriteToServer(dataReader, /*here you set some options*/);
            //}
            //catch(Exception ex){ ... } //you need no explicit try-catch here
        }

        tran.Commit(); //commit, will not be called if exception escapes
    }
}
Run Code Online (Sandbox Code Playgroud)

我已经为您添加了符合最佳实践的示例代码。