c#方法一: TransactionOptions transactionOption = new TransactionOptions(); //设置事务隔离级别 transactionOption.IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted; // 设置事务超时时间为60秒 transactionOption.Timeout = new TimeSpan(0, 0, 60); using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, transactionOption)) { int id = 0; try { //do something scope.Complete(); } catch (Exception ex) { throw ex; } finally { scope.Dispose(); } }
c#方法二: SqlTransaction sqlTransaction = sqlConnection.BeginTransaction(); SqlCommand sqlCommand = new SqlCommand(); sqlCommand.Transaction = sqlTransaction; sqlTransaction.Commit(); try { // 利用sqlcommand进行数据操作 ... // 成功提交 sqlTransaction.Commit(); } catch(Exception ex) { // 出错回滚 sqlTransaction.Rollback(); } finally { cnn.Close(); trans.Dispose(); cnn.Dispose(); }
BEGIN TRANSACTION /*--定义变量,用于累计事务执行过程中的错误--*/ DECLARE @errorSum INT SET @errorSum=0 --初始化为0,即无错误 /*--转账:张三的账户少1000元,李四的账户多1000元*/ SET @errorSum=@errorSum+@@error --累计是否有错误 IF @errorSum<>0 --如果有错误 BEGIN PRint '交易失败,回滚事务' ROLLBACK TRANSACTION --回滚 END ELSE BEGIN print '交易成功,提交事务,写入硬盘,永久的保存' COMMIT TRANSACTION --执行修改保存 END GO print '查看转账事务后的余额' GOSQL中
参考: http://www.VEVb.com/Garden-blog/archive/2011/04/21/2023417.html
新闻热点
疑难解答