在事务中尝试/捕获 - 与使用PHP或SQL有什么区别?

I'm curious about which is the best practice for using Try/Catch in a transaction. Which one would be preferable and why?

Doing the try / catch just in the PHP code:

           $dbh->begintransaction();

            try {
                $insert = "INSERT INTO test (id) VALUES(1)";
                $stpm = $dbh->prepare($insert);
                $stpm->execute();

                $dbh->commit();

            } catch (\Exception $e) {
                $dbh->rollback();
            }

Or directly in the SQL:

$insert = "BEGIN TRANSACTION;

BEGIN TRY
  INSERT INTO test (id) VALUES(1)
END TRY
BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION;
END CATCH;

IF @@TRANCOUNT > 0
    COMMIT TRANSACTION;";

$stpm = $dbh->prepare($insert);
$stpm->execute();

Use it in PHP code, so that if you have multiple queries and your PHP code fails, these queries will be aborted too.

The end result of the two options are the same. Executing a database change with the ability to rollback in the event of error. It is more a question of 'at what level do I want my integrity assurance'.

Code developers will go option 1;

DBAs will go option 2.

IMO though, I'd go option one as it separates the SQL logic execution from the intent. For whatever reason you decide to change DB technology option 1 would allow it with the least amount of effort. (If you want to get real fancy use an ORM like Doctrine, Eloquent, or even Active Record.) Wherein option 2 would requires find/replace and testing of all the possible variations.

TL;DR: Depends on what you are better at; but, abstract when possible.'

Hope this helps.

Using the PDO API or MySQL Transaction is Equal in the performance and affects, Because of PDO is just an abstraction class of SQL statements.

I Advice you to read PDO documentation on transactions, both ways are equivalent because PDO will use the driver-level transaction of a native MySQL transaction.

The Only thing you to decide if you'll perform a mixed collection of sql statements with php manipulations inside them or just a pure group of Mysql statements?