2011年11月24日 星期四

C# SqlTransaction 交易方式

SqlConnection conn = new SqlConnection(System.Web.Configuration.WebConfigurationManager.ConnectionStrings["DBconnStr"].ToString());
2 conn.Open();
3 SqlCommand command = new SqlCommand();
4 SqlTransaction transaction;
5 //Start Transaction
6 transaction = conn.BeginTransaction();
7 command.Connection = conn;
8 command.Transaction = transaction;
9 try
10 {
11    for (int i = 0; i < 5; i++)
12    {
13       command.CommandText = "insert into demouser values(newid(),'TestBatch')";
14       command.ExecuteNonQuery();
15    }
16    //Commit
17    transaction.Commit();
18 }
19 catch (Exception ex)
20 {
21   //有問題即Rollback
22     transaction.Rollback();
23 }
24 command.Connection.Close();

沒有留言:

張貼留言