runliuv

runliuv@cnblogs

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
SqlConnection sconn = null;
            SqlCommand scmd = null;
            SqlTransaction strans = null;
            try
            {
                string sqlInsert = string.Format(@"insert into MyName (myid,myfname,mymname,mylname) values 
                    ('{0}','c','c','c')", Guid.NewGuid().ToString());
                sconn = new SqlConnection(dbConnStr);
                sconn.Open();
                scmd = new SqlCommand(sqlInsert, sconn);
                strans = sconn.BeginTransaction();
                scmd.Transaction = strans;

                scmd.ExecuteNonQuery();

                strans.Commit();

                int[] myi = new int[] { 2 };
                int myr = myi[3];
            }
            catch (Exception exp)
            {
                if (strans != null && strans.Connection != null)
                    strans.Rollback();

                MessageBox.Show(exp.Message);
            }
            finally
            {
                if (sconn != null)
                    sconn.Close();
            }

 



 

如果事务完成后,还有其它代码引发异常,这时就不能去回滚事务了。事务一旦提交,它的Connection就为NULL了,可以通过if (strans != null && strans.Connection != null) 来判断。

 

posted on 2013-07-11 09:52  runliuv  阅读(3491)  评论(0编辑  收藏  举报