使用transaction处理存储数据

mac2022-06-30  111

SqlConnection s1 = new SqlConnection(WebConfigurationManager.ConnectionStrings["sqlconnstring_t1"].ConnectionString); SqlConnection s2 = new SqlConnection(WebConfigurationManager.ConnectionStrings["sqlconnstring_t2"].ConnectionString); string queryString1 = string.Empty; string queryString2 = string.Empty; queryString1 = string.Format(" insert into t1(name,pwd,email) values('{0}','{1}','{2}') ",this.TextBox1.Text,this.TextBox2.Text,this.TextBox3.Text); queryString2 = string.Format(" insert into t2(name,state) values('{0}','{1}') ",this.TextBox4.Text,this.TextBox5.Text); SqlCommand sc1 = new SqlCommand(queryString1,s1); SqlCommand sc2 = new SqlCommand(queryString2, s2); s1.Open(); SqlTransaction sqlTran1 = s1.BeginTransaction(); s2.Open(); SqlTransaction sqlTran2 = s2.BeginTransaction(); using (TransactionScope transScope = new TransactionScope())//可以不使用此引用 { try { sc1.Transaction = sqlTran1; sc1.ExecuteScalar(); sc2.Transaction = sqlTran2; sc2.ExecuteScalar(); } catch(SqlException ex) { sqlTran1.Rollback(); sqlTran2.Rollback(); s1.Close();//如果不增加数据库事务,连接关闭时,数据会写入数据库 s2.Close(); return; } sqlTran1.Commit(); sqlTran2.Commit(); transScope.Complete(); s1.Close(); s2.Close(); } } }

 

转载于:https://www.cnblogs.com/Aaron-Lee/p/7117377.html

最新回复(0)