21 TransactionOptions options = new TransactionOptions();
22 options.IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted;
23 options.Timeout = new TimeSpan(0, 2, 0);
24 using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, options))
25 {
26 try
27 {
28 using (SqlConnection sqlCn = new SqlConnection("Data Source=(local); User Id=scott; Password=tigger; Initial Catalog=Lab"))
29 {
30 SqlCommand cmd = new SqlCommand("INSERT INTO tblAccount (Account, Password, Username) VALUES (@acct, @pwd, @name)", sqlCn);
31 cmd.Parameters.Add("@acct", SqlDbType.NVarChar).Value = "EMP" + DateTime.Now.ToString("HHmmss");
32 cmd.Parameters.Add("@pwd", SqlDbType.NVarChar).Value = "PWD";
33 cmd.Parameters.Add("@name", SqlDbType.NVarChar).Value = "NAME" + DateTime.Now.ToString("HHmmss");
34 sqlCn.Open();
35 cmd.ExecuteNonQuery();
36 }
37 //** 實測結果,ODP.NET 9207不Support TransactionScope,必須用.NET 2.0的System.Data.OracleClient
38 using (OracleConnection oraCn = new OracleConnection("Data Source=MYORA; User Id=scott; Password=tigger;"))
39 {
40 OracleCommand cmd = new OracleCommand("INSERT INTO MYTABLE.tblAccount (Account, Password, Username) VALUES (:acct, :pwd, :name)", oraCn);
41 cmd.Parameters.Add(":acct", OracleType.VarChar).Value = "EMP" + DateTime.Now.ToString("HHmmss");
42 cmd.Parameters.Add(":pwd", OracleType.VarChar).Value = "PWD";
43 cmd.Parameters.Add(":name", OracleType.VarChar).Value = "NAME" + DateTime.Now.ToString("HHmmss");
44 oraCn.Open();
45 cmd.ExecuteNonQuery();
46 }
47 //在scope.Complete();後才算Commit!
48 scope.Complete();
49 }
50 catch (Exception ex)
51 {
52 //只要沒有scope.Complete(),先前的動作都會Rollback
53 Response.Write(ex.Message);
54 }
55 }