SQL事务保证数据完整性

SqlConnection myCon = new SqlConnection();
            string connectionString = System.Configuration.ConfigurationManager.AppSettings["ConnectionString"];
            myCon.ConnectionString = connectionString;

            try 
            {
                myCon.Open();

                SqlTransaction conTran = myCon.BeginTransaction();

                try
                {
                    string strCmd1 = "update T_Account set aMoney=aMoney-100 where aID='1001'";
                    SqlCommand cmd1 = new SqlCommand(strCmd1,myCon,conTran);
                    cmd1.ExecuteNonQuery();

                    throw new Exception();

                    string strCmd2 = "update T_Account set aMoney=aMoney+100 where aID='1002'";
                    SqlCommand cmd2 = new SqlCommand(strCmd2,myCon,conTran);
                    cmd2.ExecuteNonQuery();

                    
                    conTran.Commit();

                    myCon.Close();
                    Console.WriteLine("转账成功");
                }
                catch (Exception ee)
                {
                    conTran.Rollback();
                    myCon.Close();
                    Console.WriteLine("转账失败");
                }
            }
            catch (Exception ee) 
            {
                Console.WriteLine("连接数据库失败");
            }

你可能感兴趣的:(SQL事务保证数据完整性)