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) 来判断。