ADO.NET级别的事务
程序员文章站
2024-01-15 14:18:28
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 }
摘自 放羊娃
上一篇: 中国构建代码托管平台Gitee来取代微软GitHub
下一篇: php多线程读写同一文件的例子