事务在.net中的应用

  1. 只是事务应用的最简单的例子,帮助新手的
  2. public class DepManageDA
  3. {
  4.     private string CONNECT_STR = SQLHelper.CONNECTION_STRING;//SQLHelper是一个类文件,需要using一下,里面保存的都是一些经常用到的常量。
  5.     private SqlConnection sqlConnection = new SqlConnection();
  6.     private SqlDataAdapter sqlDataadapter = new SqlDataAdapter();
  7.     public DepManageDA()
  8.     {
  9.         //
  10.         // TODO: 在此处添加构造函数逻辑
  11.         //
  12.         sqlConnection = new SqlConnection(CONNECT_STR);
  13.         sqlDataadapter = new SqlDataAdapter();
  14.     }
  15.     /// <summary>
  16.     /// 添加部门
  17.     /// </summary>
  18.     /// <param name="depModel"></param>
  19.     /// <returns></returns>
  20.     public bool addDep(DepartmentModel depModel)
  21.     {
  22.         sqlConnection.Open();//打开链接
  23.         SqlCommand sqlCommand = new SqlCommand();//sql命令对象
  24.         SqlTransaction sqlTran = sqlConnection.BeginTransaction();//事务声明
  25.         sqlCommand.Connection = sqlConnection;
  26.         sqlCommand.Transaction = sqlTran;
  27.         try
  28.         {
  29.             //插入部门表
  30.             sqlCommand.CommandText = "insert into DEPART(dep_name,pub_limit,per_limit,per_num,month_curr,sub_branch) values('" + depModel.dep_name + "'," + depModel.pub_limit + "," + depModel.per_limit + "," + depModel.per_num + ",'" + depModel.month_curr + "','" + depModel.sub_branch + "')";
  31.             sqlCommand.ExecuteNonQuery();
  32.             //搜索刚加入的部门id
  33.             sqlCommand.CommandText = "select @@identity from depart";
  34.             int dep_id = int.Parse(sqlCommand.ExecuteScalar().ToString());
  35.             //插入历史表
  36.             sqlCommand.CommandText = "insert into dep_limit_his(dep_id,per_num,per_limit,limit_pub_basic,limit_per_basic) values(" + dep_id + "," + depModel.per_num + "," + depModel.per_limit + "," + depModel.pub_limit + "," + depModel.per_num * depModel.per_limit + ")";
  37.             sqlCommand.ExecuteNonQuery();
  38.             sqlTran.Commit();//事务提交
  39.             sqlConnection.Close();
  40.             return true;
  41.         }
  42.         catch (Exception e)
  43.         {
  44.             sqlTran.Rollback();//出现异常回滚
  45.             return false;
  46.         }
  47.     }
  48. }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值