我偶尔会收到此错误:sqlite3.OperationalError:无法打开数据库文件

时间:2012-05-13 17:21:03

标签: python sqlite

使用python 2.6.6,sqlite3会发生这种情况。 我有一个使用sqlite的db类。以下是其初始化的一部分。

def _init_db(self):
"init the database tables and indices"
    print '\n'.join(DROP_TABLES[0:1])
    print '\n'.join(CREATE_TABLES[0:1])
    print '\n'.join(CREATE_INDEXES[0:1])
    print '\n'.join(CREATE_TRIGGERS[0:1])
    for query in DROP_TABLES:
       self.connection.execute(query)
#   self.connection.commit()
    for query in CREATE_TABLES:
       self.connection.execute(query)
#   self.connection.commit()        
    for query in CREATE_INDEXES:
       self.connection.execute(query)
#   self.connection.commit()
    for query in CREATE_TRIGGERS:
       self.connection.execute(query)            
    self.connection.commit()

以下是查询的打印输出。 (在我看来,这不是很重要,这里是为了完整性)

DROP TABLE IF EXISTS graph_T 

CREATE TABLE IF NOT EXISTS graph_T
(v1 int,
v2 int,
step_start int,
step_end int DEFAULT 2147483647,
value int DEFAULT 1,
path_kind int DEFAULT 0,
path_id long,
partial_path_id long) 

CREATE INDEX IF NOT EXISTS idxgraph_T
          ON graph_T(v1,v2)

CREATE TRIGGER IF NOT EXISTS trig_graph_T_path_id
AFTER INSERT ON graph_T
BEGIN
UPDATE graph_T SET 
path_id = (10000 * 10000 * max(new.v1, new.v2) + 
    10000 * min(new.v1, new.v2) + 0 ) ,
partial_path_id = 10000 * 10000 * max(new.v1, new.v2) + 
    10000 * min(new.v1, new.v2)
WHERE rowid = new.rowid;
END;

我得到sqlite3.OperationalError:无法在其中一个self.connection.execute行上打开数据库文件。有时是第三或第四(它也发生在我程序的其他地方)。

我在Windows上工作。我不确定为什么会发生这种情况以及我做错了什么。 非常感谢任何建议。

更多信息(由于提出问题): - 我没有使用并发访问。没有线程或任何类似的东西。

编辑 - 更多信息:我在所有connection.execute行上添加了定时重试,它通常会失败一次或两次,然后才能正常工作。我猜测,当execute命令返回时,数据可能实际写入磁盘。

3 个答案:

答案 0 :(得分:3)

我的直觉告诉我,文件系统中必须有可疑的东西,而不是软件。也许其中一个:

  • 备份脚本正在临时移动/重命名文件或父文件夹
  • 文件系统显示为“本地”但实际上是SAN,并且存在一些间歇性问题
  • 其他面向文件系统的内核模块,例如透明加密,正在干扰SQLite系统调用
  • 入侵检测软件正在干扰SQLite系统调用
  • 另一位用户在您不知情的情况下打开文件进行阅读
  • 这是一种病毒:-)

答案 1 :(得分:2)

SQLite不适合并发访问。如果您有多个线程或进程访问同一个数据库文件,您将遇到此问题。

答案 2 :(得分:0)

并发访问答案帮助我解决了问题。我的解决方案实质上是从并发访问(https://stackoverflow.com/a/57729827/3869714)之前恢复到先前未损坏的db文件。