【发布时间】:2013-08-15 16:54:08
【问题描述】:
是否可以在 PHP 中使用带有 sqlite3 驱动程序的事务(和回滚)?我在这里没有找到信息:http://de2.php.net/manual/en/book.sqlite3.php
我不想使用 PDO...
感谢您的帮助
【问题讨论】:
标签: php sqlite transactions rollback
是否可以在 PHP 中使用带有 sqlite3 驱动程序的事务(和回滚)?我在这里没有找到信息:http://de2.php.net/manual/en/book.sqlite3.php
我不想使用 PDO...
感谢您的帮助
【问题讨论】:
标签: php sqlite transactions rollback
是的,即使没有 PDO,也可以进行事务和回滚。令人惊讶的是,要找到一个解释如何做到这一点的例子是多么困难。必须深入挖掘一些现成的代码才能找到答案。
$db=new MyDB("database.db", SQLITE3_OPEN_READWRITE);
$db->exec('BEGIN;');
$stmt=$db->prepare('UPDATE table SET name = :name WHERE id = :id');
$stmt->bindValue(':id', $id, SQLITE3_INTEGER);
$stmt->bindValue(':name', $name, SQLITE3_TEXT);
$stmt->execute();
$db->exec('COMMIT;');
逻辑来源:sombra2eternity,“MyDB”来源:php.net
【讨论】:
executeimo。在这方面有很大的错误空间。我还建议用catch 中的rollback 将其包装在try catch 中。
【讨论】:
对上述 F-3000 答案的简短扩展。如果您创建自己的类,您也可以编写自己的包装函数。例如:
class MyDB extends SQLite3 {
public function __construct(string $filename, int $flags = SQLITE3_OPEN_READWRITE | SQLITE3_OPEN_CREATE, string $encryptionKey = '') {
parent::__construct($filename, $flags, $encryptionKey);
$this->exec('PRAGMA busy_timeout = 9900');
$this->exec('PRAGMA encoding = "UTF-8"');
// more pragmas ...
}
public function enum(string $table, string $key, string $value) {
$enum = array();
$sql = "select distinct $table.$key, $table.$value
from $table
where $table.$key is not null";
if ($key !== $value) {
$sql .= "
and $table.$value is not null";
}
$sql .= "
order by null";
$result = $this->query($sql);
if ($result !== false) {
$row = $result->fetchArray(SQLITE3_NUM);
while ($row !== false) {
$enum[$row[0]] = $row[1];
$row = $result->fetchArray(SQLITE3_NUM);
}
}
return $enum;
}
public function begin() {
$this->exec('BEGIN');
}
public function commit() {
$this->exec('COMMIT');
}
public function rollback() {
$this->exec('ROLLBACK');
}
// more functions ...
} // MyDB //
【讨论】: