有哪些方法可以确保mysql事务成功完成?

时间:2011-06-10 08:34:11

标签: mysql validation

假设你有3个相关的表,你必须做3个mysql查询来插入/更新它的值。如果其中一个失败或插入了一个不合适的值,有没有办法撤消/回滚事务或设置一些约束规则,或者你总是要自己检查每个?

1 个答案:

答案 0 :(得分:2)

使用以下代码,您可以执行任何查询..但如果一个错误,则查询将被回滚。

BEGIN TRANSACTION
BEGIN TRY

    //do every query you need. if one errors it everything is off.

    COMMIT TRANSACTION
END TRY
BEGIN CATCH
   SELECT 
       ERROR_NUMBER() AS ErrorNumber,
       ERROR_SEVERITY() AS ErrorSeverity,
       ERROR_STATE() AS ErrorState,
       ERROR_PROCEDURE() AS ErrorProcedure,
       ERROR_LINE() AS ErrorLine,
       ERROR_MESSAGE() AS ErrorMessage

   ROLLBACK TRANSACTION
END CATCH