dtslobe4694 2013-10-24 18:37
浏览 128
已采纳

尝试catch,以及多个mysql insert语句。 它会接受全部还是否认所有疑问?

Hey I have question to you guys. If I implement my sql mysql insert in try catch will that prevent from executing only partial INSERT into database if one of them will fail ?

try
{
//SQL INSET TABLE 1
//SQL INSET TABLE 2
//SQL INSET TABLE 3
//SQL INSET TABLE 4
}
catch(Exception $e)
{...}

I would like to deny all or accept all. Is that they way to do that?

Regarding to your comment. I am using PDO. I would be grateful for the configuration example that would allow that.

In Your comments you often recommending transaction and rollback. Can anyone give an example with some comments on the code? x

I would also like to know if there is some alternative ways of achieving this effect.

@SOLUTION FOUND AT: PHP + MySQL transactions examples:

try {
    // First of all, let's begin a transaction
    $db->beginTransaction();

    // A set of queries; if one fails, an exception should be thrown
    $db->query('first query');
    $db->query('second query');
    $db->query('third query');

    // If we arrive here, it means that no exception was thrown
    // i.e. no query has failed, and we can commit the transaction
    $db->commit();
} catch (Exception $e) {
    // An exception has been thrown
    // We must rollback the transaction
    $db->rollback();
}

Note that, with this idea, if a query fails, an Exception must be thrown:

PDO can do that, depending on how you configure it See PDO::setAttribute and PDO::ATTR_ERRMODE and PDO::ERRMODE_EXCEPTION else, with some other API, you might have to test the result of the function used to execute a query, and throw an exception yourself.

Unfortunately, there is no magic involved. You cannot just put an instruction somewhere and have transactions done automatically: you still have to specific which group of queries must be executed in a transaction.

For example, quite often you'll have a couple of queries before the transaction (before the begin) and another couple of queries after the transaction (after either commit or rollback) and you'll want those queries executed no matter what happened (or not) in the transaction.

ANOTHER HELPFUL LINK: PHP PDO Transactions?

  • 写回答

2条回答 默认 最新

  • dongya8378 2013-10-24 18:39
    关注

    No. try/catch will NOT "undo" failed queries if one of those fails. You need a transaction:

    try {
       start transaction;
       insert 1;
       insert 2;
       ...
       commit;
    } catch {
       rollback;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度