Sqlite3, SQLSTATE[HY000]: General error: 5 database is locked

Sqlite3, SQLSTATE[HY000]: General error: 5 database is locked

我有这个小测试脚本:

session_start();
session_write_close();
error_reporting(-1);
register_shutdown_function(function() {
    //echo 'shutdown';
});

$MAX = 120;
set_time_limit($MAX);
echo date('Y-m-d H:i:s').'<br>';
$m = microtime(true);
$file_db = new PDO('sqlite:'.dirname(__FILE__).'/test.sqlite3');
$file_db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$file_db->exec("CREATE TABLE IF NOT EXISTS messages (id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT, message TEXT, time INTEGER)");

$d = date('U');
do
{
    $file_db->exec ('INSERT INTO messages VALUES (null, "titleee'.rand(1,9).'", "MESSAGEEEE'.rand(1,99).'", "'.rand(1,999).'")');
    if (date('U') - $d > $MAX/2)
    {
        break;
    }
} while (true);
$file_db = null;
echo 'ok: '.(microtime(true)-$m);

如果这是 运行 在浏览器中的多个实例,它迟早会丢弃 "SQLSTATE[HY000]: General error: 5 database is locked" 异常。怎么躲?

$file_db->exec 之后添加:sleep(2) 太多进程正试图快速插入数据库,这正在锁定 table。欢迎您尝试:实例化 $file_db 后立即 $file_db->query("SET LOCK MODE TO WAIT 120")。这应该会使脚本等待 table 解锁最多两分钟...

我遇到这个错误是因为我在 SQLiteBrowser 上有一条未保存的记录,然后 SQLite 不会在上面写入。保存记录后,我的脚本恢复正常工作。因此,每次出现此错误时,请检查您的 SQLiteBrowser(或任何其他编辑器)是否打开并且是否有任何未保存的更改。

我将锁定问题归结为虚拟机网络文件共享问题:https://www.sqlite.org/lockingv3.html#how_to_corrupt

One should note that POSIX advisory locking is known to be buggy or even unimplemented on many NFS implementations (including recent versions of Mac OS X) and that there are reports of locking problems for network filesystems under Windows. Your best defense is to not use SQLite for files on a network filesystem.

我可以通过将 SQLite 数据库文件移动到非 [=23] 的来宾 OS (Linux) 目录来解决问题=] 与主持人 OS (Windows)

在我的例子中,我将 SQLite 数据库文件移动到 Linux 来宾 OS 上的 /tmp