• 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

  • 相关阅读:
    Liferay安装maven
    html之pre标签
    a标签使用注意事项
    AngularJS学习记录
    页面不能访问,抛出 spring java.lang.IllegalArgumentException: Name for argument type [java.lang.String] 异常
    ant编译的时候,报错文件不存在,以及版本不一致
    Eclipse 更改Java 版本的方法
    总结一下本次准备环境时遇到的问题,以供下次参考
    数据上下文中的AddOrUpdate方法
    推荐一款github管理神器SourceTree
  • 原文地址:https://www.cnblogs.com/Leo_wl/p/8520803.html
Copyright © 2020-2023  润新知