C#轻量级企业事务 - TransactionScope

 1 using System;
 2 using System.Data.SqlClient;
 3 using System.Transactions;
 4
 5 namespace SomeDBTransaction
 6 {
 7     class Program
 8     {
 9         static void Main(string[] args)
10         {
11             string con1 = "SERVER=.; DATABASE=db1; UID=sa; PWD=llh";
12             string con2 = "SERVER=.; DATABASE=db2; UID=sa; PWD=llh";
13             string sqlStr1 = "U_t1";
14             string sqlStr2 = "U_t1";
15
16             int resu=CreateTransactionScope(con1, con2, sqlStr1, sqlStr2);
17             Console.WriteLine("受影响的行数:"+resu);
18
19             Console.Read();
20         }
21
22         // This function takes arguments for 2 connection strings and commands to create a transaction
23         // involving two SQL Servers. It returns a value > 0 if the transaction is committed, 0 if the
24         // transaction is rolled back. To test this code, you can connect to two different databases
25         // on the same server by altering the connection string, or to another 3rd party RDBMS by
26         // altering the code in the connection2 code block.
27         static public int CreateTransactionScope(
28             string connectString1, string connectString2,
29             string commandText1, string commandText2)
30         {
31             // Initialize the return value to zero and create a StringWriter to display results.
32             int returnValue = 0;
33             System.IO.StringWriter writer = new System.IO.StringWriter();
34
35             try
36             {
37                 // Create the TransactionScope to execute the commands, guaranteeing
38                 // that both commands can commit or roll back as a single unit of work.
39                 using (TransactionScope scope = new TransactionScope())
40                 {
41                     using (SqlConnection connection1 = new SqlConnection(connectString1))
42                     {
43                         // Opening the connection automatically enlists it in the
44                         // TransactionScope as a lightweight transaction.
45                         connection1.Open();
46
47                         // Create the SqlCommand object and execute the first command.
48                         SqlCommand command1 = new SqlCommand(commandText1, connection1);
49                         command1.CommandType = System.Data.CommandType.StoredProcedure;
50                         returnValue = command1.ExecuteNonQuery();
51                         writer.WriteLine("Rows to be affected by command1: {0}", returnValue);
52
53                         // If you get here, this means that command1 succeeded. By nesting
54                         // the using block for connection2 inside that of connection1, you
55                         // conserve server and network resources as connection2 is opened
56                         // only when there is a chance that the transaction can commit.
57                         using (SqlConnection connection2 = new SqlConnection(connectString2))
58                         {
59                             // The transaction is escalated to a full distributed
60                             // transaction when connection2 is opened.
61                             connection2.Open();
62
63                             // Execute the second command in the second database.
64                             returnValue = 0;
65                             SqlCommand command2 = new SqlCommand(commandText2, connection2);
66                             command1.CommandType = System.Data.CommandType.StoredProcedure;
67                             returnValue = command2.ExecuteNonQuery();
68                             writer.WriteLine("Rows to be affected by command2: {0}", returnValue);
69                         }
70                     }
71
72                     // The Complete method commits the transaction. If an exception has been thrown,
73                     // Complete is not  called and the transaction is rolled back.
74                     scope.Complete();
75
76                 }
77
78             }
79             catch (TransactionAbortedException ex)
80             {
81                 writer.WriteLine("TransactionAbortedException Message: {0}", ex.Message);
82             }
83             catch (ApplicationException ex)
84             {
85                 writer.WriteLine("ApplicationException Message: {0}", ex.Message);
86             }
87             catch (Exception ex)
88             {
89                 writer.WriteLine("ERROR: {0}",ex.Message);
90             }
91             // Display messages.
92             Console.WriteLine(writer.ToString());
93
94             return returnValue;
95         }
96     }
97
98
99 }

CODE

代码很简单啦 ~~,就多加了一个using而已

C#轻量级企业事务 - TransactionScope

时间: 2024-08-15 04:54:56

C#轻量级企业事务 - TransactionScope的相关文章

探索逻辑事务 TransactionScope

一.什么是TransactionScope? TransactionScope即范围事务(类似数据库中的事务),保证事务声明范围内的一切数据修改操作状态一致性,要么全部成功,要么全部失败回滚. MSDN:如果在事务范围内未不发生任何异常 (即之间的初始化 TransactionScope 对象并调用其 Dispose 方法),则范围所参与的事务可以继续,否则参与到其中的事务将回滚. 当应用程序完成所有工作时它想要在事务中执行,应调用 Complete 方法一次,以通知该事务管理器是可接受(此时事

C#中的事务TransactionScope

TransactionOptions transactionOption = new TransactionOptions(); //设置事务隔离级别 transactionOption.IsolationLevel = System.Transactions.IsolationLevel.Serializable; // 设置事务超时时间为60秒 transactionOption.Timeout = new TimeSpan(0, 0, 30); using (TransactionScop

分布式事务TransactionScope所导致几个坑

记录一下,个人见解,欢迎指正 错误: 1.该伙伴事务管理器已经禁止了它对远程/网络事务的支持. (异常来自 HRESULT:0x8004D025)2.事务已被隐式或显式提交,或已终止3.此操作对该事务的状态无效. 通过分析得到这个是与分布式事务有关的问题..有以下解决办法: 1.设置 数据库的链接字符串属性:  Enlist=false    类似于:Data Source="*;Initial Catalog=*;User ID=sa;Password=sa;Enlist=false;&quo

Python Flask+Bootstrap+Jinja2 构建轻量级企业内部系统平台框架

1.最近公司运维需求,学习python flask 满足环境治理系统的开发;入门如下;    环境类型:      Python 2.7.5         获取地址:https://www.python.org/downloads/       Flask  1.0.2               pip 安装使用模快如下:           flask==1.0.2           request==1.0.2           Jinja2==2.10           Flas

EntityFrameWork使用TransactionScope分布式事务,存储区更新、插入或删除语句影响到了意外的行数(0)。实体在加载后可能被修改或删除。刷新 ObjectStateManager 项 错误

最近在开发一个小型的物业管理系统,系统其中有一个功能需要每个月按抄的水表.电表等生成相应的费用,数据库主要的基础数据表有大楼水.电表.楼层水.电表.房间水电表:其中大楼和楼层的水电表是用于计算公摊的:系统设计有一个费用的统计表,表名ChargeAccountMaster,表内设计的有一个字段ID,主键 . 自增长:计算时由于是数据核算统计,所以引入事务计算数据的同时,也会把相应计算的结果回写回基础数据表中,计算的类是service层,框架的ORM用的是EF,就没有采用本地事务,采用了分布式事务T

事务-----2

事务:ACID 原子性,一致性,隔离性,持久性一.链接内的事务1.创建事务对象.使用链接对象的BeginTransaction()SqlTransaction trans = conn.BeginTransaction();注意:必须在链接打开的时候创建事务.2.把事务对象挂到命令对象上cmd.Transaction = trans;3.执行命令,提交与回滚事务trans.Commit() //一般放在try块中trans.Rollback() //一般放在catch块中 二.跨链接的事务 Tr

企业制度评价标准

建立企业制度的评价标准,必须先搞清楚企业规章制度的主要内容.企业规章制度的主要内容一般包含以下几点: 1.制订本制度的目的 2.本制度的主管部门及责任人 3.本制度的约束对象 4.本制度的行为规范 5.遵守制度的权益与违规责任 6.监管人员的责任 7.本制度的修改说明 8.本制度的生效或废止 清楚了规章制度的主要内容,确定评价标准就容易了. 这里的企业制度,是指单一制度,如安全管理制度.考勤管理制度.薪酬管理制度等,不是对企业制度体系的评价.单一制度的合格标准共九项. 1.编号有序. 为了确保企

谈谈分布式事务之三: System.Transactions事务详解[下篇]

在前面一篇给出的Transaction的定义中,信息的读者应该看到了一个叫做DepedentClone的方法.该方法对用于创建基于现有Transaction对 象的“依赖事务(DependentTransaction)”.不像可提交事务是一个独立的事务对象,依赖事务依附于现有的某个事务(可能是可提交事 务,也可能是依赖事务).依赖事务可以帮助我们很容易地编写一些事务型操作,当环境事务不存的时候,可以确保操作在一个独立的事务中执行:当环境事务存在 的时候,则自动加入其中. 一.依赖事务(Depen

.Net 事务

在分布式应用程序中,不可避免地会经常使用到事务控制.事务有一个开头和一个结尾,它们指定了事务的边界,事务在其边界之内可以跨越进程和计算机.事务边界内的所有资源都参与同一个事务.要维护事务边界内资源间的一致性,事务必须具备 ACID 属性,即原子性.一致性.隔离性和持续性. 1.本地事务和分布式事务 本地事务是其范围为单个可识别事务的数据资源的事务(例如,Microsoft SQL Server 数据库或 MSMQ 消息队列).例如,当单个数据库系统拥有事务中涉及的所有数据时,就可以遵循 ACID