开始交易的最佳方式是什么?

时间:2015-08-07 08:24:03

标签: php mysql pdo transactions

我在服务器上安装了cron,每3分钟运行一些功能。

这是功能:

$xmldb->sendOddsToDb();
$xmldb->copyHAtoHandicap();
$xmldb->sendFixturesToDb();
$xmldb->fillBaby();

每个功能都有:

try{
$this->conn->connect(); //connect to database
$this->PDO->beginTransaction(); // begin
$stmt = $this->PDO->prepare($this->insTLS); 
//some params not important
$this->PDO->commit(); //SAVE
$this->conn->close(); //CLOSE
}
catch(Exception $e){
$this->PDO->rollBack(); 
}

现在我的问题,最好是使用这样的事务,为每个函数新事务或者最好只启动一次,并在所有函数结束时提交? 例如:

try{
    $this->conn->connect(); //connect to database
    $this->PDO->beginTransaction(); // begin
    $xmldb->sendOddsToDb();
    $xmldb->copyHAtoHandicap();
    $xmldb->sendFixturesToDb();
    $xmldb->fillBaby();
    $this->PDO->commit(); //SAVE
    $this->conn->close(); //CLOSE
}
catch(Exception $e){
    $this->PDO->rollBack(); 
}

我需要尽可能快地向db插入数据,因为我从feed中获取数据,其中每3分钟有超过10万行。

1 个答案:

答案 0 :(得分:2)

我建议您阅读PHP PDO Transactions Documentation

首先,如果你明确地开始一个事务,执行一个PDOStatement,然后提交那个事务或者只是简单地执行事务就没有区别。

其次,如果四个数据库函数相互依赖,则将它们全部包装在事务中。

第三,无论这些功能是否相关,将它们包装在单个交易中肯定会更快。