关于.net 嵌套事务 nested transaction
connection.BeginTransaction()
此方法的事务,不能嵌套。
Error: Message "SqlConnection 不支持并行事务。" string
可以使用TransactionScope:
需要使用windows的
Distributed Transaction Coordinator (分布式事务协调器)
服务。
//Main.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.SqlClient; using System.Transactions; namespace ConsoleAppTestTranNest { class Program { static void Main(string[] args) { try { using (TransactionScope s = new TransactionScope()) { SqlConnection conn = new SqlConnection(@"Data Source=.\sql2008R2;Database=Test;User Id=sa;Password=123;Integrated Security=no;"); conn.Open(); SqlCommand cmd = conn.CreateCommand(); cmd.CommandText = "insert into aaaa values('a1')"; cmd.ExecuteNonQuery(); cmd.CommandText = "insert into aaaa values('a1')"; cmd.ExecuteNonQuery(); conn.Close(); SubClass.OperationSql(); s.Complete(); } } catch (System.Exception e) { Console.WriteLine(e.Message); } Console.WriteLine("done"); Console.ReadKey(); } } } //SubClass.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.SqlClient; using System.Transactions; namespace ConsoleAppTestTranNest { public class SubClass { public static void OperationSql() { try { using (TransactionScope s = new TransactionScope()) { SqlConnection conn = new SqlConnection(@"Data Source=.\sql2008R2;Database=Test;User Id=sa;Password=123;Integrated Security=no;"); if (conn.State != System.Data.ConnectionState.Open) conn.Open(); SqlCommand cmd = conn.CreateCommand(); cmd.CommandText = "insert into aaaa values('s1')"; cmd.ExecuteNonQuery(); int i = 0, b = 1, c; c = b / i; cmd.CommandText = "insert into aaaa values('s1')"; cmd.ExecuteNonQuery(); conn.Close(); s.Complete(); } } catch (System.Exception e) { Console.WriteLine(e.StackTrace); } } } }