参考代码:
引用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(); } }
原文地址:https://www.cnblogs.com/binlyzhuo/p/9623484.html
时间: 2024-11-01 23:49:15