- 只是事务应用的最简单的例子,帮助新手的
- public class DepManageDA
- {
- private string CONNECT_STR = SQLHelper.CONNECTION_STRING;//SQLHelper是一个类文件,需要using一下,里面保存的都是一些经常用到的常量。
- private SqlConnection sqlConnection = new SqlConnection();
- private SqlDataAdapter sqlDataadapter = new SqlDataAdapter();
- public DepManageDA()
- {
- //
- // TODO: 在此处添加构造函数逻辑
- //
- sqlConnection = new SqlConnection(CONNECT_STR);
- sqlDataadapter = new SqlDataAdapter();
- }
- /// <summary>
- /// 添加部门
- /// </summary>
- /// <param name="depModel"></param>
- /// <returns></returns>
- public bool addDep(DepartmentModel depModel)
- {
- sqlConnection.Open();//打开链接
- SqlCommand sqlCommand = new SqlCommand();//sql命令对象
- SqlTransaction sqlTran = sqlConnection.BeginTransaction();//事务声明
- sqlCommand.Connection = sqlConnection;
- sqlCommand.Transaction = sqlTran;
- try
- {
- //插入部门表
- 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 + "')";
- sqlCommand.ExecuteNonQuery();
- //搜索刚加入的部门id
- sqlCommand.CommandText = "select @@identity from depart";
- int dep_id = int.Parse(sqlCommand.ExecuteScalar().ToString());
- //插入历史表
- 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 + ")";
- sqlCommand.ExecuteNonQuery();
- sqlTran.Commit();//事务提交
- sqlConnection.Close();
- return true;
- }
- catch (Exception e)
- {
- sqlTran.Rollback();//出现异常回滚
- return false;
- }
- }
- }