当前位置:编程学习 > asp >>

ADO.NET级别的事务


  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             }
 


摘自 放羊娃
补充:Web开发 , ASP.Net ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,