62,046
社区成员
发帖
与我相关
我的任务
分享
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();
}
}
}
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;
}
}
}