• C#中的事务处理


    namespace TransactionTest
     2 {
     3 
     4   public  class Program
     5     {
     6         static void Main(string[] args)
     7         {
     8             string str ="server = .;database=Flight;uid=sa;pwd=1234";
     9             Transaction trans = new Transaction();
    10             trans.RunSqlTransaction(str);
    11         }
    12     }
    13 
    14 
    15     public class Transaction
    16     {
    17         public Transaction()
    18         {
    19 
    20         }
    21 
    22 
    23         public void RunSqlTransaction(string str)
    24         {
    25             //创建连接
    26             SqlConnection myConnection = new SqlConnection(str);
    27             //打开连接
    28             myConnection.Open();
    29             //创建命令
    30             SqlCommand myCommand = new SqlCommand();
    31 
    32             //开始事务
    33 
    34             SqlTransaction myTransaction = myConnection.BeginTransaction();
    35 
    36 
    37             //指定事务和连接对象给myCommand
    38             myCommand.Connection = myConnection;
    39             myCommand.Transaction = myTransaction;
    40             string insertStr1 = "insert into flightInfo values ('1234','济南航空公司',100,'济南','青岛')";
    41             string insertStr2 = "insert into flightInfo values ('12344','上海航空公司',100,'上海','青岛')";
    42             try
    43             {
    44                myCommand.CommandText = insertStr1;
    45 
    46                //执行更新
    47                 myCommand.ExecuteNonQuery();
    48 
    49 
    50                 myCommand.CommandText = insertStr2;
    51                 //执行更新
    52                 myCommand.ExecuteNonQuery();
    53                 //提交事务
    54                 myTransaction.Commit();
    55 
    56                 //默认情况下,事务不提交则回滚
    57                 Console.WriteLine("两条记录插入成功");
    58             }
    59             catch (Exception ex)
    60             {
    61                 try
    62                 {
    63                     //回滚事务
    64                     myTransaction.Rollback();
    65                 }
    66                 catch (Exception ex1)
    67                 {
    68 
    69                     Console.WriteLine(ex1.ToString());
    70                 }
    71                 Console.WriteLine(ex.ToString());
    72             }
    73             finally
    74             {
    75                 myConnection.Close();
    76 
    77             }
    78 
    79         }
    80     }
    81 }
    82 
  • 相关阅读:
    领域驱动模型DDD(二)——领域事件的订阅/发布实践
    领域驱动模型DDD(一)——服务拆分策略
    js创建对象的多种方式
    java.net.SocketException: Connection reset 异常处理
    hive从入门到放弃(四)——分区与分桶
    《前端运维》五、k8s3灰度发布、滚动更新与探针
    《前端运维》五、k8s2pod、services与Ingress部署
    《前端运维》三、Docker2其他
    《前端运维》三、Docker1镜像与容器
    《前端运维》二、Nginx3静态资源服务、跨域与其他
  • 原文地址:https://www.cnblogs.com/chenbg2001/p/1604072.html
Copyright © 2020-2023  润新知