Add try to pdo execute


Add try to pdo execute

下面的代码在数据库中添加数据

    $sth = $this->db->prepare('UPDATE `adwords_clients_google` set status = 2');
    $sth->execute();
    $sth = null;  

    $sth = $this->db->prepare('
        INSERT INTO
            `adwords_clients_google`
            (`client_foreign_id`, `status`, `client_name`, `client_currency`)
        VALUES
            (:id, 1, :name, :currency)
        ON DUPLICATE KEY UPDATE
            `status` = VALUES(`status`),
            `client_name` = VALUES(`client_name`),
            `client_currency` = VALUES(`client_currency`)
    ');
    $sth->bindParam(':id', $id);
    $sth->bindParam(':name', $name);
    $sth->bindParam(':currency', $currency);
    foreach($accounts as $account) {
        $id = $account->customerId;
        $name = $account->name;
        $currency = $account->currencyCode;
        $sth->execute();         
    }

我想在这里添加try,类似

        try {
        if ($sth->execute()) {
            helper::putToLog('ok queryCampaignArr, inserted rows: ' . $sth->rowCount());
        } else {
            helper::putToLog('not ok', true);
        }
    } catch (Exception $ex) {
        helper::putToLog($sth->debugDumpParams(), true);
        helper::putToLog("ERROR: ".$ex->getMessage(), true);
    }

但我不知道我应该为每一行添加它吗?我该怎么做?

如果使用PDO连接DB,则使用PDOException类来处理异常。

try {
    if ($sth->execute()) {
        helper::putToLog('ok queryCampaignArr, inserted rows: ' . $sth->rowCount());
    } else {
        helper::putToLog('not ok', true);
    }
} catch (PDOException  $ex) {
    $Exception->getMessage(); // Error message
   (int)$Exception->getCode(); // Error Code
}