You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PDO连接SQLite数据库时Catch分支未执行的问题

SQLite PDO自动创建数据库文件问题的解决方法

这是因为SQLite的PDO驱动默认行为就是如果指定的数据库文件不存在,会自动创建该文件,所以这种场景下不会触发连接异常,catch分支也就不会执行。

解决方法分两种场景:

场景1:需要读写数据库(优先使用)

在创建PDO实例前,先检查目标数据库文件是否存在:

$dbPath = __DIR__ . "/database.db";
try {
    // 先验证文件是否存在
    if (!file_exists($dbPath)) {
        throw new Exception("Database file missing");
    }
    $db = new PDO("sqlite:" . $dbPath);
    echo "Connected";
} catch (Exception $e) {
    echo "Unable to connect to the database!";
}

场景2:仅需读取数据库

可以通过PDO连接参数指定只读模式打开数据库,这样当文件不存在时会直接抛出异常:

try {
    $db = new PDO(
        "sqlite:" . __DIR__ . "/database.db",
        null,
        null,
        [PDO::SQLITE_ATTR_OPEN_FLAGS => PDO::SQLITE_OPEN_READONLY]
    );
    echo "Connected";
} catch (Exception $e) {
    echo "Unable to connect to the database!";
}

注意:只读模式下无法执行任何写入操作(比如INSERT、UPDATE),如果业务需要读写,务必使用第一种方法。

内容的提问来源于stack exchange,提问作者Karmen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 22:25:17