C#-MSSql事务写法示例

using System.Data.SqlClient;



1
string idStr="123"; 2 using (SqlConnection conn = new SqlConnection(Appconfig.GetMSSQLStr())) 3 { 4 5 conn.Open(); 6 using (SqlTransaction trans = conn.BeginTransaction()) 7 { 8 try 9 { 10 SqlCommand cmd = new SqlCommand(); 11 cmd.Connection = conn; 12 cmd.Transaction = trans; 13 14 StringBuilder strHead = new StringBuilder(); 15 strHead.AppendLine("*********日志记录**********:"); 16 strHead.AppendLine("......"); 17 strHead.AppendLine("*********日志记录**********:"); 18 Appconfig.WriteLogFile(strHead.ToString(), "日志文件"); 19 20 string chksql = ""; 21 #region sql语句1 22 chksql = @"select * from table1 where id='{0}'"; 23 24 chksql = string.Format(chksql, idStr); 25 26 cmd.CommandText = chksql; 27 cmd.ExecuteNonQuery(); 28 #endregion 29 30 #region sql语句2 31 chksql = @"select * from table2 where id='{0}'"; 32 33 chksql = string.Format(chksql, idStr); 34 35 cmd.CommandText = chksql; 36 cmd.ExecuteNonQuery(); 37 #endregion 38 39 40 trans.Commit(); 41 42 StringBuilder strHead = new StringBuilder(); 43 resultlog.AppendLine("执行完毕"); 44 Appconfig.WriteLogFile(resultlog.ToString(), "日志文件"); 45 46 } 47 catch (Exception ex) 48 { 49 trans.Rollback(); 50 StringBuilder str = new StringBuilder(); 51 Appconfig.WriteLogFile(str.ToString(), "日志文件"); 52 } 53 } 54 conn.Close(); 55 }
posted @ 2021-10-12 10:57  ꧁执笔小白꧂  阅读(239)  评论(0编辑  收藏  举报