准备工作
- 添加 System.Transactions 引用(在解决方案的网站上右键);
- 引用 System.Transactions 名称空间。
示例讲解
using (var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection String"].ConnectionString)) { using (var ct = new CommittableTransaction()) { conn.Open(); conn.EnlistTransaction(ct);//关联事务 using (var cmd = new SqlCommand()) { cmd.Connection = conn; cmd.CommandType = CommandType.Text; try { cmd.CommandText = "insert into TranTable(Priority) values(1)"; cmd.ExecuteNonQuery(); cmd.CommandText = "insert into TranTable(Priority) values(256)"; cmd.ExecuteNonQuery(); ct.Commit(); Response.Write("Ok"); } catch (SqlException ex) { ct.Rollback(); Response.Write("Error:" + ex.Message); } } } conn.Close(); }
参考:http://msdn.microsoft.com/zh-cn/library/ms172146(v=vs.90).aspx