zoukankan      html  css  js  c++  java
  • c#中事务及回滚

    程序一般在特殊数据的时候,会有数据上的同步,这个时候就用到了事物。闲话不多说,直接上代码。

     1 public void UpdateContactTableByDataSet(DataSet ds, string strTblName)
     2         {
     3             try
     4             {
     5                 SqlDataAdapter myAdapter = new SqlDataAdapter();
     6                 SqlConnection conn = new SqlConnection("connection string");
     7                 SqlCommand myCommand = new SqlCommand("select * from strTblName", conn);
     8                 myAdapter.SelectCommand = myCommand;
     9                 SqlCommandBuilder myCommandBuilder = new SqlCommandBuilder(myAdapter);
    10 
    11                 conn.Open();
    12                 SqlTransaction myTrans = conn.BeginTransaction();
    13                 myCommand.Transaction = myTrans;
    14 
    15                 try
    16                 {
    17                     myAdapter.Update(ds, strTblName);
    18                     myTrans.Commit();
    19                 }
    20                 catch (Exception e)
    21                 {
    22                     try
    23                     {
    24                         myTrans.Rollback();//回滚并取消数据库的更新
    25                     }
    26                     catch (SqlException ex)
    27                     {
    28                         if (myTrans.Connection != null)
    29                         {
    30                             Console.WriteLine("回滚失败! 异常类型: " + ex.GetType());
    31                         }
    32                     }
    33                 }
    34                 finally
    35                 {
    36                     conn.Close();
    37                 }
    38 
    39             }
    40             catch (Exception ex)
    41             {
    42                 throw ex;
    43             }
    44         }

    事务回滚主要用于提交失败。(lock)用于处理并发事件。

  • 相关阅读:
    Hadoop学习笔记1:伪分布式环境搭建
    VMware 下的CentOS6.7 虚拟机与Windows7通信
    CentOS6.7 下安装JDK
    [HDU 1430] 魔板
    数码问题合集
    [light oj 1328] A Gift from the Setter
    [light oj 1013] Love Calculator
    [POJ 1151] Atlantis
    关于12月28日到12月29日
    [HDU 1199] Color the Ball
  • 原文地址:https://www.cnblogs.com/felix-wang/p/6723981.html
Copyright © 2011-2022 走看看