• 事务 代码


    Action<Transaction, string> action = (t, str) =>
    {
    SqlConnection con
    = new SqlConnection("server=.;uid=sa;pwd=chen;database=pubs");
    con.Open();
    if(null != con)
    con.EnlistTransaction(t);
    string strSql = "insert into test values('" + str + "','zzz','zzz')";
    SqlCommand cmd
    = new SqlCommand(strSql, con);
    Console.WriteLine(cmd.ExecuteNonQuery());
    con.Close();
    };

    using(CommittableTransaction ctran =new CommittableTransaction())
    {
    try
    {
    action(ctran,
    "123645");
    ctran.Commit();
    }
    catch(Exception ex)
    {
    Console.WriteLine(ex.Message);
    ctran.Rollback();
    }
    }

    //依赖事务处理

    Action
    <object> DepAction= t =>
    {
    DependentTransaction de
    = t as DependentTransaction;
    action(de, DateTime.Now.Second.ToString());
    Thread.Sleep(
    3000);
    de.Rollback();
    };

    using(CommittableTransaction ctran = new CommittableTransaction())
    {
    try
    {
    action(ctran, DateTime.Now.Second.ToString()
    + "Com");
    new Thread(delegate(object obj) { DepAction(obj); }).Start(ctran.DependentClone(DependentCloneOption.BlockCommitUntilComplete));
    /*
    * BlockCommitUntilComplete 跟事务Commit之前,等待所有依赖事务提交
    * RollbackIfNotComplete 跟事务Commit时,依赖事务没有提交,则终止整个事务
    */
    ctran.Commit();
    }
    catch(Exception ex)
    {
    Console.WriteLine(ex.Message);
    ctran.Rollback();
    }
    }


    //环境事务处理
    using(TransactionScope scope = new TransactionScope())
    {
    Transaction.Current.TransactionCompleted
    += (s, e) => {
    Console.WriteLine(e.Transaction.TransactionInformation.ToString());
    };
    scope.Dispose();
    }
  • 相关阅读:
    初学mysql数据库
    类与对象课堂总结
    CNN网络的基本介绍(三)
    CNN网络的基本介绍(二)
    CNN网络的基本介绍(一)
    Android studio界面布局的简单介绍
    Android studio初见及结构分析
    JDBC实现Mysqual的增删改查
    BufferedReader统计TXT文本
    JAVA的异常处理
  • 原文地址:https://www.cnblogs.com/blackman/p/2080635.html
Copyright © 2020-2023  润新知