简体   繁体   English

Sqlite3,OperationalError:无法打开数据库文件

[英]Sqlite3, OperationalError: unable to open database file

Question: Why can't I open the database?问题:为什么我无法打开数据库?


Info: I'm working on a project using sqlite3 database.信息:我正在使用sqlite3数据库进行项目。 I wrote a test program that runs and passes it the database:我编写了一个运行并将其传递给数据库的测试程序:

/tmp/cer/could.db

The unit test program can make the db without any problem.单元测试程序可以使db没有任何问题。 But, when I actually use the program passing the same location to it, i got below error:但是,当我实际使用将相同位置传递给它的程序时,出现以下错误:

OperationalError: unable to open database file OperationalError:无法打开数据库文件

I've tried doing it with:我试过这样做:

1) an empty database.
2) the database and the unit test left behind.
3) no database at all.

In three cases, I got the above error.在三种情况下,我得到了上述错误。 The most frustrating part has to be the fact that the unittest can do it just fine, but the actual program can't.最令人沮丧的部分是unittest可以做到这一点,但实际程序却做不到。

Any clues as to what on earth is going on?关于地球上发生了什么的任何线索?

Primary diagnosis: SQLite is unable to open that file for some reason.初步诊断:SQLite 由于某种原因无法打开该文件。

Checking the obvious reasons why, and in approximate order that I recommend checking:检查明显的原因,并按照我建议检查的大致顺序:

  • Is the program running on the same machine as you're testing it?该程序是否与您正在测试它在同一台机器上运行?
  • Is it running as you (or at least the same user as you're testing it as)?它是否像您一样运行(或至少与您测试它的用户相同)?
  • Is the disk containing /tmp full?包含/tmp的磁盘是否已满? (You're on Unix, so use df /tmp to find out.) (您使用的是 Unix,因此请使用df /tmp来查找。)
  • Does the /tmp/cer directory have “odd” permissions? /tmp/cer目录是否有“奇数”权限? (SQLite needs to be able to create additional files in it in order to handle things like the commit log.) (SQLite 需要能够在其中创建其他文件才能处理诸如提交日志之类的事情。)
  • Is the unit test code still using that database?单元测试代码是否仍在使用该数据库? (Concurrent opens are possible with a modern-enough SQLite and when in the right filesystem — though /tmp is virtually always on the right sort of FS so it's probably not that — but it's still not recommended.) (使用足够现代的 SQLite 并且在正确的文件系统中时,并发打开可能的 - 尽管/tmp实际上总是在正确的 FS 上,所以它可能不是这样 - 但仍然不推荐。)
  • Is the development code really trying to write to that database, or is something “clever” catching you out and causing it to try to open something else?开发代码是否真的试图写入该数据库,或者是“聪明”的东西抓住了你并导致它试图打开其他东西? (I've been caught out by this in my code in the past; don't think it can't happen to you…) (我过去在我的代码中被这个问题所困扰;不要认为它不会发生在你身上……)
  • Are you using the same version of the SQLite library in the unit tests and the production code?您是否在单元测试和生产代码中使用相同版本的 SQLite 库?

If you're not on the same machine, it's quite possible that the production system doesn't have a /tmp/cer directory.如果您不在同一台机器上,则生产系统很可能没有/tmp/cer目录。 Obvious to fix that first.显然要先解决这个问题。 Similarly, if you're on the same machine but running as different users, you're likely to have permissions/ownership problems.同样,如果您在同一台机器上但以不同的用户身份运行,您可能会遇到权限/所有权问题。 Disk space is another serious gotcha, but less likely.磁盘空间是另一个严重的问题,但可能性较小。 I don't think it's the last three, but they're worth checking if the more obvious deployment problems are sorted.我不认为这是最后三个,但如果对更明显的部署问题进行了排序,它们值得检查。 If it's none of the above, you've hit an exotic problem and will have to report much more info (it might even be a bug in SQLite, but knowing the developers of it, I believe that to be quite unlikely).如果以上都不是,那么您遇到了一个奇怪的问题并且将不得不报告更多信息(它甚至可能是 SQLite 中的一个错误,但了解它的开发人员,我认为这不太可能)。

This worked for me:这对我有用:

conn = sqlite3.connect("C:\\users\\guest\\desktop\\example.db")

Note: Double slashes in the full path注意:完整路径中的双斜杠

Using python v2.7 on Win 7 enterprise and Win Xp Pro在 Win 7 企业版和 Win Xp Pro 上使用python v2.7

Hope this helps someone.希望这可以帮助某人。

On unix I got that error when using the ~ shortcut for the user directory.在 unix 上,使用用户目录的~快捷方式时出现该错误。 Changing it to /home/user resolved the error.将其更改为/home/user解决了该错误。

One reason might be running the code in a path that doesn't match with your specified path for the database.一个原因可能是在与您为数据库指定的路径不匹配的路径中运行代码。 For example if in your code you have:例如,如果在您的代码中,您有:

conn = lite.connect('folder_A/my_database.db')

And you run the code inside the folder_A or other places that doesn't have a folder_A it will raise such error.并且您在folder_A或其他没有folder_A的地方运行代码会引发此类错误。 The reason is that SQLite will create the database file if it doesn't exist not the folder.原因是如果数据库文件不存在而不是文件夹,SQLite 将创建数据库文件。

One other way for getting around this problem might be wrapping your connecting command in a try-except expression and creating the directory if it raises sqlite3.OperationalError .解决此问题的另一种方法可能是将连接命令包装在try-except表达式中,并在引发sqlite3.OperationalError时创建目录。

from os import mkdir import sqlite3 as lite从 os 导入 mkdir 导入 sqlite3 作为 lite

try:
    conn = lite.connect('folder_A/my_database.db')
except lite.OperationalError:
    mkdir('folder_A')
finally:
    conn = lite.connect('folder_A/my_database.db')

in my case, i tried creating the sqlite db in /tmp folder and from all the slashes i missed a single slash就我而言,我尝试在/tmp文件夹中创建 sqlite db,并且从所有斜杠中我错过了一个斜杠

Instead of sqlite:///tmp/mydb.sqlite -> sqlite:////tmp/mydb.sqlite ...而不是sqlite:///tmp/mydb.sqlite -> sqlite:////tmp/mydb.sqlite ...

Ran into this issue while trying to create an index on a perfectly valid database.尝试在完全有效的数据库上创建索引时遇到此问题。 Turns out it will throw this error (in addition to other reasons described here) if the sqlite temp_store_directory variable/directory is unwritable.事实证明,如果 sqlite temp_store_directory变量/目录不可写,它将引发此错误(除了此处描述的其他原因)。

Solution: change temp_store_directory with c.execute(f'PRAGMA temp_store_directory = "{writable_directory}"') .解决方案:用c.execute(f'PRAGMA temp_store_directory = "{writable_directory}"')更改temp_store_directory Note that this pragma is being deprecated and I am not yet sure what the replacement will be.请注意,此编译指示 已被弃用,我还不确定替换将是什么。

I faced the same problem on Windows 7. My database name was test and I got the error:我在 Windows 7 上遇到了同样的问题。我的数据库名称是test ,我得到了错误:

self.connection = Database.connect(**kwargs)
sqlite3.OperationalError: unable to open database file

I replaced test with test.db and and all went smooth.我用test.db替换了test ,一切都很顺利。

In my case, the solution was to use an absolute path, to find an existing file:就我而言,解决方案是使用绝对路径来查找现有文件:

import os.path
filepath = os.path.abspath(filepath)
# Leave this out if the file doesn't exist yet
assert os.path.exists(filepath), "The file doesn't exist"
conn = sqlite3.connect(filepath)

I don't know why this fix works: the path only contained ASCII characters and no spaces.我不知道为什么这个修复有效:路径只包含 ASCII 字符,没有空格。 Still it made the difference.尽管如此,它还是有所作为。

For reference: Windows 7, Python 3.6.5 (64-bit).供参考:Windows 7、Python 3.6.5(64 位)。

I was not able to reproduce the issue on another machine (also Windows 7, Python 3.6.4 64-bit), so I have no idea why this fix works.我无法在另一台机器(也是 Windows 7、Python 3.6.4 64 位)上重现该问题,所以我不知道为什么此修复程序有效。

import sqlite3

connection = sqlite3.connect("d:\\pythonAPI\\data.db")
cursor = connection.cursor()
create_table = "CREATE TABLE users (id int, username text, password text)"
cursor.execute(create_table)


for clearer full path if you didn't get it clear如果您没有弄清楚,可以获得更清晰的完整路径

Use the fully classified name of database file使用数据库文件的完全分类名称

Use- /home/ankit/Desktop/DS/Week-7-MachineLearning/Week-7-MachineLearning/soccer/database.sqlite使用-/home/ankit/Desktop/DS/Week-7-MachineLearning/Week-7-MachineLearning/soccer/database.sqlite

instead-反而-

If this happens randomly after correctly being able to access your database (and no settings have changed), it could be a result of a corrupted database .如果在能够正确访问您的数据库后随机发生这种情况(并且没有更改任何设置),则可能是由于数据库损坏

I got this error after trying to write to my database from two processes at the same time and it must have corrupted my db.sqlite3 file.尝试同时从两个进程写入我的数据库后出现此错误,它一定损坏了我的 db.sqlite3 文件。

My solution was to revert back to a previous commit before the corruption happened.我的解决方案是在损坏发生之前恢复到以前的提交。

Run into the error on Windows, added assert os.path.exists, double checked the path, run the script as administrator, nothing helped.在 Windows 上遇到错误,添加了 assert os.path.exists,仔细检查了路径,以管理员身份运行脚本,没有任何帮助。

Turns out if you add your folders to the Windows Defender's Ransomware Protection, you can no longer use other programs to write there unless you add these programs to the Controlled Folder Access' whitelist.事实证明,如果您将文件夹添加到 Windows Defender 的勒索软件保护中,除非您将这些程序添加到受控文件夹访问的白名单中,否则您将无法再使用其他程序在那里写入。

Solution - check if your folder has been added to the Windows Defender's Ransomware Protection and remove it for faster fix.解决方案 - 检查您的文件夹是否已添加到 Windows Defender 的勒索软件保护中并将其删除以便更快地修复。

The only thing you need to do is create the folder (as it doesn't exist already), only the database file will be created by the program.您唯一需要做的就是创建文件夹(因为它不存在),程序只会创建数据库文件。 This really worked for me!这真的对我有用!

This is definitely a permissions issue.这绝对是权限问题。 If someone is getting this error on linux, make sure you're running the command with sudo as the file most likely is owned by root.如果有人在 linux 上遇到此错误,请确保您使用sudo运行该命令,因为该文件很可能归 root 所有。 Hope that helps!希望有帮助!

1) Verify your database path, check in your settings.py 1)验证你的数据库路径,检查你的settings.py

DATABASES = {
    'default': {
        'CONN_MAX_AGE': 0,
        'ENGINE': 'django.db.backends.sqlite3',
        'HOST': 'localhost',
        'NAME': os.path.join(BASE_DIR, 'project.db'),
        'PASSWORD': '',
        'PORT': '',
        'USER':''

some times there wont be NAME': os.path.join(BASE_DIR, 'project.db'),有时不会有 NAME': os.path.join(BASE_DIR, 'project.db'),

2)Be sure for the permission and ownership to destination folder 2)确保目标文件夹的权限和所有权

it worked for me,它对我有用,

My reason was very foolish.我的理由很愚蠢。 I had dropped the manage.py onto the terminal so it was running using the full path.我已将 manage.py 放到终端上,因此它使用完整路径运行。 And I had changed the name of the folder of the project.我已经更改了项目文件夹的名称。 So now, the program was unable to find the file with the previous data and hence the error.所以现在,程序无法找到包含先前数据的文件,因此出现错误。

Make sure you restart the software in such cases.确保在这种情况下重新启动软件。

For any one who has a problem with airflow linked to this issue.对于与此问题相关的气流问题的任何人。

In my case, I've initialized airflow in /root/airflow and run its scheduler as root .就我而言,我已经在/root/airflow并将其调度程序作为root运行。 I used the run_as_user parameter to impersonate the web user while running task instances.我在运行任务实例时使用了run_as_user参数来模拟Web用户。 However airflow was always failing to trigger my DAG with the following errors in logs:但是,气流始终无法触发我的 DAG,并在日志中出现以下错误:

sqlite3.OperationalError: unable to open database file
...
sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) unable to open database file

I also found once I triggered a DAG manually, a new airflow resource directory was automatically created under /home/web .我还发现,一旦我手动触发了 DAG,就会在/home/web下自动创建一个新的气流资源目录。 I'm not clear about this behavior, but I make it work by removing the entire airflow resources from /root , reinitializing airflow database under /home/web and running the scheduler as web under:我不清楚这种行为,但我通过从/root删除整个气流资源,重新初始化/home/web下的气流数据库并将调度程序作为web运行来使其工作:

[root@host ~]# rm -rf airflow
[web@host ~]$ airflow initdb
[web@host ~]$ airflow scheduler -D

If you want to try this approach, I may need to backup your data before doing anything.如果你想尝试这种方法,我可能需要在做任何事情之前备份你的数据。

Make sure you are not editing the settings.py file while trying to run syncdb, you will get the same error!!!确保在尝试运行 syncdb 时没有编辑 settings.py 文件,你会得到同样的错误!!!

self.connection = Database.connect(**kwargs)
sqlite3.OperationalError: unable to open database file

有同样的问题,但最佳答案对我来说太长了,所以我建议打开另一个 shell 窗口类型cd #enter

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 内存sqlite3数据库中经常出现“ OperationalError:无法打开数据库文件” - Frequent “OperationalError: unable to open database file” with in memory sqlite3 database IronPython SQLite3 OperationalError:无法打开数据库文件 - IronPython SQLite3 OperationalError: unable to open database file Flask OperationalError:无法使用sqlite3打开数据库文件 - Flask OperationalError: unable to open database file using sqlite3 OperationalError“无法打开数据库文件”使用SQLAlchemy和SQLite3处理查询结果 - OperationalError “unable to open database file” processing query results with SQLAlchemy and SQLite3 sqlite3.OperationalError:无法打开数据库文件 - sqlite3.OperationalError: unable to open database file sqlite3.OperationalError:无法打开数据库文件 - sqlite3.OperationalError: unable to open database file GAE,sqlite3.OperationalError:无法打开数据库文件 - GAE, sqlite3.OperationalError: unable to open database file Docker sqlite3.OperationalError:无法打开数据库文件 - Docker sqlite3.OperationalError: unable to open database file Python sqlite3.OperationalError:无法打开数据库文件 - Python sqlite3.OperationalError: unable to open database file OperationalError:无法打开数据库文件 - OperationalError: unable to open database file
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM