按书上的说法,使用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','设计部','北京','[email protected]')", conn);
cmd.ExecuteNonQuery();
cmd = new SqlCommand("insert into employee values(8,'B','程序部','上海','[email protected]')", conn);
cmd.ExecuteNonQuery();
this.Label1.Text = "OK!";
}
catch(Exception ex)
{
this.Label1.Text = ex.Message;
}
}
trans.Complete();
}
}
}TransactionScope回滚失败insert
违反了 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','设计部','北京','[email protected]')", conn);
cmd.ExecuteNonQuery();
cmd = new SqlCommand("insert into employee values(8,'B','程序部','上海','[email protected]')", conn);
cmd.ExecuteNonQuery();
this.Label1.Text = "OK!";
}
catch(Exception ex)
{
this.Label1.Text = ex.Message;
}
}
trans.Complete();
}
}
}TransactionScope回滚失败insert
在catch里面加上
trans.Rollback()
{
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','设计部','北京','[email protected]')", conn);
cmd.ExecuteNonQuery();
cmd = new SqlCommand("insert into employee values(8,'B','程序部','上海','[email protected]')", conn);
cmd.ExecuteNonQuery();
this.Label1.Text = "OK!";
}
trans.Complete();
}
}
catch(Exception ex)
{
this.Label1.Text = ex.Message;
}
}
}