如何防止 SQLITE SQLSTATE[HY000] [14]?

2021-12-26 00:00:00 persistent php pdo sqlite

我有时会收到以下错误:

I receive sometimes the following error:

SQLSTATE[HY000] [14] 无法打开数据库文件

SQLSTATE[HY000] [14] unable to open database file

我使用

new PDO("sqlite:database/datbase.db","","",array(
    PDO::ATTR_PERSISTENT => true
));

每次我想从数据库读取数据或向数据库写入数据时.打开过程是如下函数:

everytime I want read or write data from or to the database. The open process is the following function:

function opendatabase(){
try{
    return new PDO("sqlite:database/database.db","","",array(
        PDO::ATTR_PERSISTENT => true
    ));
}catch(PDOException $e){
    logerror($e->getMessage(), "opendatabase");
    print "Error in openhrsedb ".$e->getMessage();
}
}

一段时间后(有时一个多小时,有时几分钟后,我收到帖子开头的错误消息.我该如何防止此类错误?

After some time (sometime more than an hour, some times after some minutes I get the error message at the beginning of the post. How can I prevent such error?

推荐答案

这是来自 SQLlite 的错误:

This is an error from SQLlite :

#define SQLITE_CANTOPEN 14/* 无法打开数据库文件 */

好像你打开了很多连接,建议你打开的连接重用.

It seems like you have opened to many connections, I suggest you to reuse the connection if it is open.

创建属性:

private $pdo;

并在创建新对象之前检查它是否为空:

And check if it's null before creating a new object:

function opendatabase(){
    try{
        if($this->pdo==null){
          $this->pdo =new PDO("sqlite:database/database.db","","",array(
                PDO::ATTR_PERSISTENT => true
            ));
        }
        return $this->pdo;
    }catch(PDOException $e){
        logerror($e->getMessage(), "opendatabase");
        print "Error in openhrsedb ".$e->getMessage();
    }
}

相关文章