SqlBulkCopy 参数配置示例

SqlBulkCopy 参数配置示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
SqlConnection sqlConn = new SqlConnection( sourceConnection) ;
            sqlConn.Open() ;
 
            SqlTransaction tran = sqlConn.BeginTransaction();
 
            SqlCommand commandInsert = new SqlCommand("insert into [test_sqlbulk_update]( b ) values (1) ", sqlConn, tran);
 
            int result = commandInsert.ExecuteNonQuery();
 
            SqlCommand commandSourceData = new SqlCommand("select * from test_sqlbulk ", sqlConn, tran);
             
            SqlDataReader reader = commandSourceData.ExecuteReader();
             
            // Set up the bulk copy object using the KeepIdentity option.
            using (SqlBulkCopy bulkCopy = new SqlBulkCopy(sqlConn, SqlBulkCopyOptions.KeepIdentity, tran))
            {
                bulkCopy.BatchSize = 2;
                bulkCopy.DestinationTableName =
                    "dbo.test_sqlbulk_des";
 
                // Write from the source to the destination.
                // This should fail with a duplicate key error
                // after some of the batches have been copied.
                try
                {
                    bulkCopy.WriteToServer(reader);
                    reader.Close();
                    tran.Commit();
                }
                catch (Exception ex)
                {
                    reader.Close();
                    tran.Rollback();<br>            // tran.Commit(); 异常仍提交执行,同时注释上一行。
                }
                
            }

 => 异常时执行 rollback, 最终结果:没做任何修改.

=> 外部事务,Catch 中执行 Commint ,发生异常,因为自动回滚了,但在Catch 执行 Rollback 无异常。

 View Code

原文地址:https://www.cnblogs.com/Leo_wl/p/8520803.html