C# SqlTransaction事务,先从后主

 using (SqlConnection connection = new SqlConnection(connectionString))
            {

                //事务启动是通过connection来开启
                connection.Open();
                SqlTransaction trans = connection.BeginTransaction();//开启一个事务
                SqlCommand cmd = new SqlCommand();//利用SqlCommand执行任务
                //为挂起的本地事务将事务对象和连接部分分配给命令对象
                cmd.Connection = connection;
                cmd.Transaction = trans;
                try
                {
                    //删除
                    cmd.CommandText = "delete T_User_Info where  Id='1'";
                    cmd.CommandType = CommandType.Text;
                    cmd.Parameters.Clear();
                    cmd.ExecuteNonQuery();
                    //添加
                    cmd.CommandText = "insert into T_User_Info (Id,Name) values('1','某某')";
                    cmd.CommandType = CommandType.Text;
                    cmd.Parameters.Clear();
                    cmd.ExecuteNonQuery();
                    trans.Commit();//提交事务,代表所有的事务已经提交到数据库
                }
                catch (Exception ex)
                {
                    //catch特定用法,从挂起状态滚回事务
                    trans.Rollback();
                    Console.WriteLine(ex.Message);
                }
                connection.Close();
            }

 

posted on 2020-09-25 18:18  小乐丶  阅读(404)  评论(0编辑  收藏  举报