private static void Execute(string connectionString) { using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); SqlTransaction transaction; using (SqlCommand cmd = connection.CreateCommand()) { //啟動事務 transaction = connection.BeginTransaction(); cmd.Connection = connection; cmd.Transaction = transaction; try { cmd.CommandText = "sql語句!"; cmd.ExecuteNonQuery(); //完成提交 transaction.Commit(); } catch(Exception ex) { //數據回滾 transaction.Rollback(); throw ex; } } } }
在ADO.NET中使用SqlTransaction事務的例子代碼,需要說明的已經寫成注釋。參考:http://www.cnblogs.com/wang726zq/archive/2012/05/17/Transaction.html