一、运行事务
要使用事务来运行你的查询,你可以使用 $this->db->trans_start() 和 $this->db->trans_complete() 两个方法
$this->db->trans_start();
$this->db->query('AN SQL QUERY...');
$this->db->query('ANOTHER QUERY...');
$this->db->query('AND YET ANOTHER QUERY...');
$this->db->trans_complete();
在 start 和 complete 之间,你可以运行任意多个查询,根据查询执行 成功或失败,系统将自动提交或回滚。
二、错误处理
如果你的数据库配置文件 config/database.php 中启用了错误报告(db_debug = TRUE), 当提交没有成功时,你会看到一条标准的错误信息。如果没有启用错误报告, 你可以像下面这样来管理你的错误:
$this->db->trans_start();
$this->db->query('AN SQL QUERY...');
$this->db->query('ANOTHER QUERY...');
$this->db->trans_complete();
if ($this->db->trans_status() === FALSE)
{
// generate an error... or use the log_message() function to log your error
}
三、手工运行事务
$this->db->trans_begin();
$this->db->query('AN SQL QUERY...');
$this->db->query('ANOTHER QUERY...');
$this->db->query('AND YET ANOTHER QUERY...');
if ($this->db->trans_status() === FALSE)
{
$this->db->trans_rollback();
}
else
{
$this->db->trans_commit();
}
手动运行事务时,请务必使用 $this->db->trans_begin() 方法, 而不是 $this->db->trans_start() 方法。