SQLServer同一实例下事务操作
Posted 过客
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SQLServer同一实例下事务操作相关的知识,希望对你有一定的参考价值。
参考代码:
引用Dapper
public bool OrderAdd2(User user, Order order) { string dbString = ConfigurationManager.ConnectionStrings["TDB"].ConnectionString; string db2String = ConfigurationManager.ConnectionStrings["TDB2"].ConnectionString; SqlConnection conn = new SqlConnection(dbString); SqlConnection conn2 = new SqlConnection(db2String); conn.Open(); conn2.Open(); SqlTransaction tran = conn.BeginTransaction(); SqlTransaction tran2 = conn2.BeginTransaction(); //SqlCommand cmd = conn.CreateCommand(); //cmd.CommandText = $"insert into [User](USex,UName)values(‘{user.USex}‘,‘{user.UName}‘)"; //cmd.Transaction = tran; //SqlCommand cmd2 = conn2.CreateCommand(); //cmd2.CommandText = $"insert into [Order](UID,Date)values(‘{order.UID}‘,‘{order.Date}‘)"; //cmd2.Transaction = tran2; string cmdTxt = $"insert into [User](USex,UName)values(@USex,@UName)"; string cmdTxt2 = $"insert into [Order](UID,Date)values(@UID,@Date)"; try { //cmd.ExecuteNonQuery(); //cmd2.ExecuteNonQuery(); conn.Execute(cmdTxt,user,tran); conn2.Execute(cmdTxt2, order, tran2); tran.Commit(); tran2.Commit(); return true; } catch (Exception ex) { tran.Rollback(); tran2.Rollback(); return false; } finally { conn.Close(); conn2.Close(); } }
以上是关于SQLServer同一实例下事务操作的主要内容,如果未能解决你的问题,请参考以下文章