欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

ADO.NET级别的事务

程序员文章站 2022-05-08 12:31:47
  View Code    1  string sqlcon = "server=.;database=webSyste...

  View Code
 
 1  string sqlcon = "server=.;database=webSystem;uid=sa;pwd=";
 2             SqlConnection myConnection = new SqlConnection(sqlcon);//建立数据库连接对象
 3             myConnection.Open();
 4           
 5             //启动一个事务
 6             SqlTransaction sqltrans = myConnection.BeginTransaction();
 7
 8             //为事务创建一个命令
 9             SqlCommand cmd = new SqlCommand();
10             cmd.Connection = myConnection;
11             cmd.Transaction = sqltrans;
12             try
13             {
14                 cmd.CommandText = "update dbo.Sys_LoginUser set UserName='allen' where UID='19'";
15                 cmd.ExecuteNonQuery();
16                 cmd.CommandText = "update dbo.Sys_LoginUser  set URealName='wankui' where UID='19'";
17                 cmd.ExecuteNonQuery();
18                 sqltrans.Commit();//提交,为了事务处理可以成功完成必须条用SqlTransaction的commit()方法
19                 Response.Write("两条数据修改成功");
20
21             }
22             catch (Exception ex)
23             {
24                 sqltrans.Rollback();//如果发生错误,回滚
25                 Response.Write(ex);
26             }
27             finally
28             {
29                 myConnection.Close();//关闭数据库连接
30             }
 


摘自 放羊娃