首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > asp.net >

TransactionScope没自动回滚

2013-03-17 
TransactionScope没有自动回滚?按书上的说法,使用TransactionScope创建事务代码块(在数据库表中插入两条记

TransactionScope没有自动回滚?
按书上的说法,使用TransactionScope创建事务代码块(在数据库表中插入两条记录),运行后显示
违反了 PRIMARY KEY 约束 'PK_Employee'。不能在对象 'dbo.Employee' 中插入重复键。 语句已终止。
这个是预期的,但查数据表后,发现第一条insert语句成功插入了,没有回滚?

代码如下,烦劳指导一下:

protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                using (TransactionScope trans = new TransactionScope())
                {
                    using (SqlConnection conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["DotNetDb"].ConnectionString))
                    {
                        try
                        {
                            conn.Open();
                            SqlCommand cmd;
                            cmd = new SqlCommand("insert into employee values(8,'A','设计部','北京','a@126.com')", conn);
                            cmd.ExecuteNonQuery();
                            cmd = new SqlCommand("insert into employee values(8,'B','程序部','上海','b@sohu.com')", conn);
                            cmd.ExecuteNonQuery();
                            this.Label1.Text = "OK!";
                        }
                        catch(Exception ex)
                        {
                            this.Label1.Text = ex.Message;
                        }
                    }


                    trans.Complete();
                }
            }
        }

TransactionScope 回滚 失败 insert
[解决办法]
你的代码没有事务回滚操作。
在catch里面加上
trans.Rollback()

[解决办法]
问题的症结在这里

trans.Complete();

Complete会交将事务提交(commit),所以出错前的SQL当前就执行了,将你的代码改成下面这样就行了

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        try
        {
            using (TransactionScope trans = new TransactionScope())
            {
                using (SqlConnection conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["DotNetDb"].ConnectionString))
                {
                    conn.Open();
                    SqlCommand cmd;
                    cmd = new SqlCommand("insert into employee values(8,'A','设计部','北京','a@126.com')", conn);
                    cmd.ExecuteNonQuery();
                    cmd = new SqlCommand("insert into employee values(8,'B','程序部','上海','b@sohu.com')", conn);
                    cmd.ExecuteNonQuery();
                      this.Label1.Text = "OK!";
                }
                
                trans.Complete();
            }
        }
        catch(Exception ex)
        {
            this.Label1.Text = ex.Message;
        }
    }
}

热点排行