专注网页设计制作教程: http://www.update8.com

Asp.net 在三层架构中事务的使用

时间:2012-02-02 09:42点击: 次 【

    再我知道的.net中,执行事务有两种方法,一种是自动事物,使用起来相当简单,但是需要配置服务器,如果你用的是web共享主机,即没有权限配置自己的服务器,那就没必要用这种了,接下了我讲下.net中最普通的事务SqlTransaction。

         接触3层也有一段时间了,了解水平一般,前段时间在想在三层中怎么使用事务呢,放在哪呢?Sqlherper ?    DAL?   BLL?。然后我就疯狂的百度,好几次都是未果(因为做的都是小项目,不用事务也关系不大),今天我再次查时,好好的看了csdn上的以讨论,http://topic.csdn.net/u/20091101/19/f21697d7-8f0c-4eb3-8e59-d0fe2f0b04b0.html,结合前辈和高手们的意见,自己改了一个出来。我的想法是将事务逻辑写在业务逻辑层,数据库的处理还都是在SQLHELPER,BLL层通过事务SqlTransaction传值访问DAL,再访问Sqlhelper。接下来是分块的代码。

 

Sqlhelper:

 1 public static SqlTransaction BeginTransaction()
 2         {
 3             SqlConnection myConnection = new SqlConnection(DbConfig.ConnectionString);
 4             myConnection.Open();
 5             SqlTransaction tran = myConnection.BeginTransaction();
 6             return tran;
 7         }
 8 
 9 public int ExecutenQuery(string cmdtxt, SqlParameter[] paras, CommandType cmdtype, SqlTransaction tran)
10         {
11             int res;
12             try
13             {
14                 Cmd = new SqlCommand(cmdtxt, tran.Connection);
15                 Cmd.Transaction = tran;
16                 Cmd.CommandType = cmdtype;
17                 Cmd.Parameters.AddRange(paras);
18                 res = Cmd.ExecuteNonQuery();
19             }
20             catch (Exception ex)
21             {
22                 FileHelper.WriteMyLog(ex);
23                 throw ex;
24             }
25             return res;
26         }

 

DAL:

1 public bool test(int i,SqlTransaction tran)
2         {
3             string sql = "insert into [test]([item]) values(@i)";
4             SqlParameter[] paras=new SqlParameter[]{new SqlParameter("@i",i)};
5             return sqlhelper.ExecutenQuery(sql, paras, CommandType.Text, tran)>0;
6         }

BLL:
 1 UserDAO userdao = new UserDAO();
 2         public bool test()
 3         {
 4             using (SqlTransaction tran = SQLHelper.BeginTransaction())
 5             {
 6                 try
 7                 {
 8                     userdao.test(2, tran);
 9                     userdao.test(256, tran);
10                     tran.Commit(); return true;
11                 }
12                 catch
13                 {
14                     tran.Rollback();
15                     return false;
16                 }
17                 finally
18                 {
19                     tran.Connection.Close();//关闭数据库连接
20 } 21 } 22 }

上述代码在此次测试中通过,若要用于真实项目中,请修改后再使用,还有本人水平一般,写的不到之处请大家见谅。

------分隔线----------------------------