C#使用事务

using (SqlConnection conn = new SqlConnection(Connstring)
       {
           conn .Open();

           // 开启一个事务
           SqlTransaction sqlTran = conn .BeginTransaction();

           // Enlist a command in the current transaction.
           SqlCommand command = conn .CreateCommand();
           //begin transaction
           command.Transaction = sqlTran;   

           try
           {
               // 执行sql语句
command.CommandText ="xxxxx"; command.ExecuteNonQuery(); command.CommandText ="yyyyyy"; command.ExecuteNonQuery(); // 提交
sqlTran.Commit(); } catch (Exception ex) { // 执行失败回滚操作. lblMsg.Text = ex.Message; try { // 回滚. sqlTran.Rollback(); } catch (Exception exRollback) { // 异常
lblMsg.Text = exRollback.Message; } } }

 

posted @ 2015-12-07 15:05  你的_班主任  阅读(139)  评论(0编辑  收藏  举报