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

What is the best way to begin transactions?

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

这是函数:

$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(); 
}

我需要尽可能快地将数据插入数据库,因为我每 3 分钟从 Feed 中获取超过 100 000 行的数据。

我建议阅读这篇 PHP PDO Transactions Documentation

首先,如果您显式开始一个事务、执行一个 PDOStatement 并提交该事务或只是简单地执行该事务,都没有区别。

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

第三,无论功能是否相关,将它们包装在一个事务中肯定会更快。