使用transaction处理存储数据
Posted Aaron_M
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用transaction处理存储数据相关的知识,希望对你有一定的参考价值。
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(); } } }
以上是关于使用transaction处理存储数据的主要内容,如果未能解决你的问题,请参考以下文章
MySQL ------ 事务处理(transaction)(二十八)
SpringBoot设置 @Transactional ,并在异常处理中调用setRollbackOnly()事务不回滚