Sqlite3, SQLSTATE[HY000]: 一般错误:5 数据库被锁定

Joh*_*ith 5 php sqlite

我有这个小测试脚本:

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);
Run Code Online (Sandbox Code Playgroud)

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

Lui*_*ese 8

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


Jus*_*n E 2

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