2011-06-23 92 views
5

我有一個簡單的嘗試捕獲,這是不是我所期望的操作。這是我第一次嘗試使用事務與PDO:PHP PDO交易問題

try 
     { 
      $dbo = Db::init(); 
      $dbo->beginTransaction(); 
      $dbo->exec("TRUNCATE TABLE {$this->table}"); 
      $dbo->exec($insert); 
      $dbo->commit(); 
     } 
     catch(Exception $e) 
     { 
      $dbo->rollBack(); 
      echo 'Failed to sync ' . $this->table; 
     } 

的問題是,如果$dbo->exec($insert);失敗,則$dbo->exec("TRUNCATE TABLE {$this->table}");不會被回滾。有任何想法嗎?

+0

什麼是'$ insert'? – tplaner

+0

一個字符串(正在工作)。但是,如果我故意在其中引入語法錯誤以使其引發異常,那麼它在回滾時不會回滾到表的擦除發生之前 – grep

回答

7

TRUNCATE無法回滾。改爲使用DELETE

+0

由此保留表以及它的結構?我只想刪除數據而不是表格本身。 – grep

+0

@Headspin:'DELETE FROM table' ---將刪除所有的行(儘管它會更慢,但支持回滾) – zerkms

+0

@Headspin:'DELETE FROM tablename' – zerkms

4

假設你使用的是MySQL,TRUNCATE TABLE有一個隱含的COMMIT。從http://dev.mysql.com/doc/refman/5.0/en/truncate-table.html的文檔:

As of MySQL 5.0.8, truncate operations cause an implicit commit. Before 5.0.8, truncate operations are not transaction-safe; an error occurs when attempting one in the course of an active transaction.