全部执行
protected void Button2_Click(object sender, EventArgs e) { // 执行事务 SqlConnection con = new SqlConnection(str); con.Open(); SqlTransaction tran = con.BeginTransaction(); try { SqlCommand cmd1 = new SqlCommand("INSERT INTO Code( name ) VALUES ( 'ww1')", con); SqlCommand cmd2 = new SqlCommand("INSERT INTO Code( name ) VALUES ( 'ww2')", con); cmd1.Transaction = tran; cmd2.Transaction = tran; cmd1.ExecuteNonQuery(); cmd2.ExecuteNonQuery(); tran.Commit(); } catch { tran.Rollback(); } finally { con.Close(); GetData(); } }
执行带保存点的事务
protected void Button3_Click(object sender, EventArgs e) { // 执行带保存点的事务 // 执行事务 SqlConnection con = new SqlConnection(str); con.Open(); SqlTransaction tran = null; tran = con.BeginTransaction(); try { SqlCommand cmd1 = new SqlCommand("INSERT INTO Code( name ) VALUES ( 'ww3')", con); SqlCommand cmd2 = new SqlCommand("INSERT INTO Code( name ) VALUES ( 'ww4')", con); cmd1.Transaction = tran; cmd1.ExecuteNonQuery(); tran.Save("One"); cmd2.Transaction = tran; cmd2.ExecuteNonQuery(); tran.Rollback("One"); tran.Commit(); } catch { tran.Rollback(); } finally { con.Close(); GetData(); } }
效果图