Question: Why can’t I open the database?
Info: I’m working on a project using sqlite3
database. 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. But, when I actually use the program passing the same location to it, i got below error:
OperationalError: unable to open database file
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.
Any clues as to what on earth is going on?
shiva
5,0035 gold badges23 silver badges42 bronze badges
asked Jan 9, 2011 at 0:23
NarcolapserNarcolapser
5,84515 gold badges45 silver badges56 bronze badges
5
Primary diagnosis: SQLite is unable to open that file for some reason.
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? (You’re on Unix, so usedf /tmp
to find out.) - Does the
/tmp/cer
directory have “odd” permissions? (SQLite needs to be able to create additional files in it in order to handle things like the commit log.) - 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.) - 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?
If you’re not on the same machine, it’s quite possible that the production system doesn’t have a /tmp/cer
directory. 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).
answered Jan 9, 2011 at 0:41
Donal FellowsDonal Fellows
132k18 gold badges147 silver badges214 bronze badges
6
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
Hope this helps someone.
answered Dec 26, 2011 at 18:38
2
On unix I got that error when using the ~
shortcut for the user directory.
Changing it to /home/user
resolved the error.
answered Jul 11, 2017 at 16:02
JacquotJacquot
1,75014 silver badges25 bronze badges
2
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. The reason is that SQLite will create the database file if it doesn’t exist not the folder.
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
.
from os import mkdir
import sqlite3 as 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')
answered Apr 2, 2017 at 14:12
MazdakMazdak
104k18 gold badges159 silver badges188 bronze badges
4
in my case, i tried creating the sqlite db in /tmp
folder and from all the slashes i missed a single slash
Instead of sqlite:///tmp/mydb.sqlite
-> sqlite:////tmp/mydb.sqlite
…
answered Oct 5, 2020 at 12:21
Ricky LeviRicky Levi
7,1441 gold badge57 silver badges64 bronze badges
3
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.
Solution: change temp_store_directory
with c.execute(f'PRAGMA temp_store_directory = "{writable_directory}"')
. Note that this pragma is being deprecated and I am not yet sure what the replacement will be.
answered Nov 22, 2019 at 17:41
AlopexAlopex
3232 silver badges8 bronze badges
I faced the same problem on Windows 7. My database name was test
and I got the error:
self.connection = Database.connect(**kwargs)
sqlite3.OperationalError: unable to open database file
I replaced test
with test.db
and and all went smooth.
answered Dec 14, 2013 at 15:54
FallenFallen
4,4052 gold badges26 silver badges44 bronze badges
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. Still it made the difference.
For reference: Windows 7, Python 3.6.5 (64-bit).
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.
answered Apr 15, 2018 at 21:42
pj.dewittepj.dewitte
4623 silver badges10 bronze badges
1
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
fmw42
45.6k9 gold badges62 silver badges79 bronze badges
answered Jun 24, 2018 at 22:15
1
Use the fully classified name of database file
Use- /home/ankit/Desktop/DS/Week-7-MachineLearning/Week-7-MachineLearning/soccer/database.sqlite
instead-
answered Nov 29, 2018 at 12:15
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.
My solution was to revert back to a previous commit before the corruption happened.
answered Aug 30, 2019 at 15:48
Run into the error on Windows, added assert os.path.exists, double checked the path, run the script as administrator, nothing helped.
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.
Solution — check if your folder has been added to the Windows Defender’s Ransomware Protection and remove it for faster fix.
answered Sep 19, 2019 at 9:02
TH TodorovTH Todorov
1,10911 silver badges25 bronze badges
1
Make sure you are not editing the settings.py file while trying to run syncdb, you will get the same error!!!
self.connection = Database.connect(**kwargs)
sqlite3.OperationalError: unable to open database file
Doug Porter
7,7114 gold badges39 silver badges55 bronze badges
answered Nov 23, 2011 at 20:59
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!
answered Mar 29, 2018 at 13:30
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. Hope that helps!
answered Oct 3, 2018 at 18:37
tzndrtzndr
173 bronze badges
1
1) Verify your database path,
check in your 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’),
2)Be sure for the permission and ownership to destination folder
it worked for me,
answered Mar 15, 2019 at 3:33
My reason was very foolish.
I had dropped the manage.py onto the terminal so it was running using the full path.
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.
answered Sep 14, 2019 at 17:11
The DoctorThe Doctor
4861 gold badge6 silver badges16 bronze badges
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. I used the run_as_user
parameter to impersonate the web user while running task instances. However airflow was always failing to trigger my DAG with the following errors in logs:
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
. 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@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.
answered Nov 15, 2019 at 22:08
micmiamicmia
1,3611 gold badge14 silver badges29 bronze badges
Вопрос: Почему я не могу открыть базу данных?
Информация: Я работаю над проектом, цель которого не важна, но использует базу данных sqlite3. Я сделал тестовую программу, которая запускает и передает ей местоположение для создания базы данных:
/tmp/cer/could.db
а программа unit test может сделать db без проблем. Затем я фактически использую программу, передавая ей одно и то же место, и он говорит
OperationalError: невозможно открыть файл базы данных
Я пытался сделать это с пустой базой данных. с базой данных unit test, оставленной позади, и без базы данных вообще. во всех трех случаях я получаю эту ошибку. Самая неприятная часть должна состоять в том, что unit test может сделать это просто отлично, но фактическая программа не может.
Любые подсказки о том, что происходит на Земле?
Ответ 1
Первичный диагноз: SQLite не может открыть этот файл по какой-либо причине.
Проверка очевидных причин, почему и в примерном порядке, который я рекомендую проверить:
- Работает ли программа на том же компьютере, что и вы ее тестируете?
- Он работает как вы (или, по крайней мере, тот же пользователь, что и вы его тестируете)?
- Полный диск, содержащий
/tmp
? (Вы находитесь в Unix, поэтому используйтеdf /tmp
, чтобы узнать.) - Имеет ли каталог
/tmp/cer
«нечетные» разрешения? (SQLite должен иметь возможность создавать в нем дополнительные файлы, чтобы обрабатывать такие вещи, как журнал фиксации.) - Является ли код unit test все еще использующим эту базу данных? (Параллельные открытия возможны с помощью современного SQLite и в правильной файловой системе, хотя
/tmp
практически всегда находится в правильном порядке FS, поэтому он, вероятно, не тот, но он по-прежнему не рекомендуется.) - Является ли код разработки действительно попыткой писать в эту базу данных или что-то «умное» ловит вас и заставляет его пытаться открыть что-то еще? (Я был пойман этим в моем коде в прошлом, не думаю, что это не может случиться с вами…)
- Используете ли вы ту же версию библиотеки SQLite в модульных тестах и производственный код?
Если вы не на одной машине, вполне возможно, что в производственной системе нет каталога /tmp/cer
. Очевидно, чтобы это исправить. Точно так же, если вы находитесь на одной машине, но работаете как разные пользователи, у вас могут возникнуть проблемы с правами/правами собственности. Дисковое пространство — еще одна серьезная проблема, но менее вероятно. Я не думаю, что это последние три, но стоит проверить, отсортированы ли более очевидные проблемы с развертыванием. Если это не так, вы столкнулись с экзотической проблемой и должны будете сообщить гораздо больше информации (это может быть даже ошибкой в SQLite, но, зная разработчиков, я считаю, что это маловероятно).
Ответ 2
Это сработало для меня:
conn = sqlite3.connect("C:\users\guest\desktop\example.db")
Примечание. Двойные слэши в полном пути
Использование python v2.7 для Win 7 Enterprise и Win Xp Pro
Надеюсь, это поможет кому-то.
Ответ 3
В unix я получил эту ошибку при использовании ярлыка ~
для каталога пользователя.
Изменение его на /home/user
разрешило ошибку.
Ответ 4
Одной из причин может быть запуск кода в пути, который не соответствует указанному пути для базы данных. Например, если в вашем коде есть:
conn = lite.connect('folder_A/my_database.db')
И вы запустите код внутри folder_A
или других мест, у которых нет folder_A
, он вызовет такую ошибку. Причина в том, что SQLite создаст файл базы данных, если он не существует, а не в папке.
Другим способом обойти эту проблему может быть объединение вашей команды соединения в выражении try-except
и создание каталога, если оно вызывает sqlite3.OperationalError
.
from os import 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')
Ответ 5
Убедитесь, что вы не редактируете файл settings.py при попытке запустить syncdb, вы получите ту же ошибку!!!
self.connection = Database.connect(**kwargs)
sqlite3.OperationalError: unable to open database file
Ответ 6
Я столкнулся с той же проблемой в Windows 7. Мое имя базы данных было test
, и я получил ошибку:
self.connection = Database.connect(**kwargs)
sqlite3.OperationalError: unable to open database file
Я заменил test
на test.db
, и все прошло гладко.
Ответ 7
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':''
иногда не будет NAME ‘: os.path.join(BASE_DIR,’ project.db ‘),
2) Убедитесь в разрешении и праве собственности на папку назначения
это сработало для меня,
Ответ 8
Единственное, что вам нужно сделать, это создать папку (так как она еще не существует), программа создаст только файл базы данных.
Это действительно сработало для меня!
Ответ 9
В моем случае решение было использовать абсолютный путь, чтобы найти существующий файл:
import os.path
filepath = os.path.abspath(filepath)
# Leave this out if the file does not exist yet
assert os.path.exists(filepath), "The file does not exist"
conn = sqlite3.connect(filepath)
Я не знаю, почему это исправление работает: путь содержал только символы ASCII и без пробелов. Тем не менее, это имело значение.
Для справки: Windows 7, Python 3.6.5 (64-разрядная версия).
Мне не удалось воспроизвести проблему на другом компьютере (также Windows 7, Python 3.6.4 64-bit), поэтому я понятия не имею, почему это исправление работает.
Ответ 10
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)
для более ясного полного пути, если вы не поняли его
Ответ 11
Это определенно проблема с разрешениями. Если кто-то получает эту ошибку в Linux, убедитесь, что вы запускаете команду с sudo
, поскольку файл, скорее всего, принадлежит пользователю root. Надеюсь, это поможет!
Ответ 12
Используйте полностью классифицированное имя файла базы данных
Use-/home/ankit/Desktop/DS/Week-7-MachineLearning/Week-7-MachineLearning/soccer/database.sqlite
instead-
Ответ 13
Если это происходит случайным образом после правильного доступа к вашей базе данных (и никакие настройки не изменились), это может быть результатом поврежденной базы данных.
Я получил эту ошибку после попытки записи в базу данных из двух процессов одновременно, и она, должно быть, повредила мой файл db.sqlite3.
Мое решение состояло в том, чтобы вернуться к предыдущей фиксации до того, как произошло повреждение.
Ответ 14
Моя причина была очень глупой.
Я поместил файл manage.py на терминал, чтобы он работал по полному пути.
И я изменил название папки проекта.
Поэтому теперь программе не удалось найти файл с предыдущими данными и, следовательно, с ошибкой.
Убедитесь, что вы перезапустите программное обеспечение в таких случаях.
Ответ 15
Запустил ошибку в Windows, добавил assert os.path.exists, дважды проверил путь, запустил скрипт от имени администратора, ничего не помогло.
Оказывается, если вы добавите свои папки в Защиту вымогателя Windows Defender, вы больше не сможете использовать для записи другие программы, если вы не добавите эти программы в белый список доступа к контролируемым папкам.
Решение — проверьте, была ли ваша папка добавлена в Защиту вымогателей Windows Defender, и удалите ее для более быстрого исправления.
Using my Django app, I’m able to read from the database just fine. When the application didn’t have permission to access the file, it gave me this error:
attempt to write a readonly database
Which made sense. So I edited the permissions on the file, so that the Apache process had write permissions. However, instead of it being able to write, I get this cryptic error:
unable to open database file
If it’s useful, here’s the entire output:
Request Method: POST
Request URL: http://home-sv-1/hellodjango1/polls/1/vote/
Exception Type: OperationalError
Exception Value:
unable to open database file
Exception Location: /usr/lib/pymodules/python2.5/django/db/backends/sqlite3/base.py in execute, line 193
Python Executable: /usr/bin/python
Python Version: 2.5.2
Python Path: ['/var/www', '/usr/lib/python2.5', '/usr/lib/python2.5/plat-linux2', '/usr/lib/python2.5/lib-tk', '/usr/lib/python2.5/lib-dynload', '/usr/local/lib/python2.5/site-packages', '/usr/lib/python2.5/site-packages', '/usr/lib/pymodules/python2.5', '/usr/lib/pymodules/python2.5/gtk-2.0']
Server time: Sun, 23 Aug 2009 07:06:08 -0500
Let me know if a stack trace is necessary.
Спасибо большое, разобралась)
Добавлено через 7 часов 12 минут
Продолжаю войну с sqlite.
Вот этот код:
C# | ||
|
стопорится на строчке cmd.Dispose(). Программа отключается. ни ошибок, ни эксепшенов. Программа завершается с каким-то невероятным кодом. + вот такой сумасшедший набор?
‘WindowsFormsApplication1.vshost.exe’ (CLR v4.0.30319: WindowsFormsApplication1.vshost.exe): Loaded ‘C:WindowsMicrosoft.NetassemblyGAC_64mscorlibv4.0_4.0.0.0__b77a5c561934e08 9mscorlib.dll’. Skipped loading symbols. Module is optimized and the debugger option ‘Just My Code’ is enabled.
‘WindowsFormsApplication1.vshost.exe’ (CLR v4.0.30319: WindowsFormsApplication1.vshost.exe): Loaded ‘C:WindowsassemblyGAC_MSILMicrosoft.VisualStudio.HostingProcess.Utilities12 .0.0.0__b03f5f7f11d50a3aMicrosoft.VisualStudio.HostingProcess.Utilities.dll’. Skipped loading symbols. Module is optimized and the debugger option ‘Just My Code’ is enabled.
‘WindowsFormsApplication1.vshost.exe’ (CLR v4.0.30319: WindowsFormsApplication1.vshost.exe): Loaded ‘C:WindowsMicrosoft.NetassemblyGAC_MSILSystem.Windows.Formsv4.0_4.0.0.0__b 77a5c561934e089System.Windows.Forms.dll’. Skipped loading symbols. Module is optimized and the debugger option ‘Just My Code’ is enabled.
‘WindowsFormsApplication1.vshost.exe’ (CLR v4.0.30319: WindowsFormsApplication1.vshost.exe): Loaded ‘C:WindowsMicrosoft.NetassemblyGAC_MSILSystem.Drawingv4.0_4.0.0.0__b03f5f7 f11d50a3aSystem.Drawing.dll’. Skipped loading symbols. Module is optimized and the debugger option ‘Just My Code’ is enabled.
‘WindowsFormsApplication1.vshost.exe’ (CLR v4.0.30319: WindowsFormsApplication1.vshost.exe): Loaded ‘C:WindowsMicrosoft.NetassemblyGAC_MSILSystemv4.0_4.0.0.0__b77a5c561934e08 9System.dll’. Skipped loading symbols. Module is optimized and the debugger option ‘Just My Code’ is enabled.
‘WindowsFormsApplication1.vshost.exe’ (CLR v4.0.30319: WindowsFormsApplication1.vshost.exe): Loaded ‘C:WindowsassemblyGAC_MSILMicrosoft.VisualStudio.HostingProcess.Utilities.Sy nc12.0.0.0__b03f5f7f11d50a3aMicrosoft.VisualStudio.HostingProcess.Utilities.Sy nc.dll’. Skipped loading symbols. Module is optimized and the debugger option ‘Just My Code’ is enabled.
‘WindowsFormsApplication1.vshost.exe’ (CLR v4.0.30319: WindowsFormsApplication1.vshost.exe): Loaded ‘C:WindowsassemblyGAC_MSILMicrosoft.VisualStudio.Debugger.Runtime12.0.0.0__ b03f5f7f11d50a3aMicrosoft.VisualStudio.Debugger.Runtime.dll’. Skipped loading symbols. Module is optimized and the debugger option ‘Just My Code’ is enabled.
‘WindowsFormsApplication1.vshost.exe’ (CLR v4.0.30319: WindowsFormsApplication1.vshost.exe): Loaded ‘D:ПользователиМои документырабочий столDocumentsVisual Studio 2013ProjectsWindowsFormsApplication1WindowsFormsApplication1binx64Release WindowsFormsApplication1.vshost.exe’. Skipped loading symbols. Module is optimized and the debugger option ‘Just My Code’ is enabled.
‘WindowsFormsApplication1.vshost.exe’ (CLR v4.0.30319: WindowsFormsApplication1.vshost.exe): Loaded ‘C:WindowsMicrosoft.NetassemblyGAC_MSILSystem.Corev4.0_4.0.0.0__b77a5c5619 34e089System.Core.dll’. Skipped loading symbols. Module is optimized and the debugger option ‘Just My Code’ is enabled.
‘WindowsFormsApplication1.vshost.exe’ (CLR v4.0.30319: WindowsFormsApplication1.vshost.exe): Loaded ‘C:WindowsMicrosoft.NetassemblyGAC_MSILSystem.Xml.Linqv4.0_4.0.0.0__b77a5c 561934e089System.Xml.Linq.dll’. Skipped loading symbols. Module is optimized and the debugger option ‘Just My Code’ is enabled.
‘WindowsFormsApplication1.vshost.exe’ (CLR v4.0.30319: WindowsFormsApplication1.vshost.exe): Loaded ‘C:WindowsMicrosoft.NetassemblyGAC_MSILSystem.Data.DataSetExtensionsv4.0_4 .0.0.0__b77a5c561934e089System.Data.DataSetExtensions.dll’. Skipped loading symbols. Module is optimized and the debugger option ‘Just My Code’ is enabled.
‘WindowsFormsApplication1.vshost.exe’ (CLR v4.0.30319: WindowsFormsApplication1.vshost.exe): Loaded ‘C:WindowsMicrosoft.NetassemblyGAC_MSILMicrosoft.CSharpv4.0_4.0.0.0__b03f5 f7f11d50a3aMicrosoft.CSharp.dll’. Skipped loading symbols. Module is optimized and the debugger option ‘Just My Code’ is enabled.
‘WindowsFormsApplication1.vshost.exe’ (CLR v4.0.30319: WindowsFormsApplication1.vshost.exe): Loaded ‘C:WindowsMicrosoft.NetassemblyGAC_64System.Datav4.0_4.0.0.0__b77a5c561934 e089System.Data.dll’. Skipped loading symbols. Module is optimized and the debugger option ‘Just My Code’ is enabled.
‘WindowsFormsApplication1.vshost.exe’ (CLR v4.0.30319: WindowsFormsApplication1.vshost.exe): Loaded ‘C:WindowsMicrosoft.NetassemblyGAC_MSILSystem.Deploymentv4.0_4.0.0.0__b03f 5f7f11d50a3aSystem.Deployment.dll’. Skipped loading symbols. Module is optimized and the debugger option ‘Just My Code’ is enabled.
‘WindowsFormsApplication1.vshost.exe’ (CLR v4.0.30319: WindowsFormsApplication1.vshost.exe): Loaded ‘C:WindowsMicrosoft.NetassemblyGAC_MSILSystem.Xmlv4.0_4.0.0.0__b77a5c56193 4e089System.Xml.dll’. Skipped loading symbols. Module is optimized and the debugger option ‘Just My Code’ is enabled.
‘WindowsFormsApplication1.vshost.exe’ (CLR v4.0.30319: WindowsFormsApplication1.vshost.exe): Loaded ‘C:WindowsMicrosoft.NetassemblyGAC_MSILmscorlib.resourcesv4.0_4.0.0.0_ru_b 77a5c561934e089mscorlib.resources.dll’. Module was built without symbols.
The thread 0x2418 has exited with code 259 (0x103).
The thread 0x15b8 has exited with code 259 (0x103).
The thread 0x1c2c has exited with code 0 (0x0).
The thread 0x18b8 has exited with code 259 (0x103).
‘WindowsFormsApplication1.vshost.exe’ (CLR v4.0.30319: WindowsFormsApplication1.vshost.exe): Loaded ‘D:ПользователиМои документырабочий столDocumentsVisual Studio 2013ProjectsWindowsFormsApplication1WindowsFormsApplication1binx64Release WindowsFormsApplication1.exe’. Symbols loaded.
‘WindowsFormsApplication1.vshost.exe’ (CLR v4.0.30319: WindowsFormsApplication1.vshost.exe): Loaded ‘D:ПользователиМои документырабочий столDocumentsVisual Studio 2013ProjectsWindowsFormsApplication1WindowsFormsApplication1binx64Release System.Data.SQLite.dll’. Symbols loaded.
‘WindowsFormsApplication1.vshost.exe’ (CLR v4.0.30319: WindowsFormsApplication1.vshost.exe): Loaded ‘C:WindowsMicrosoft.NetassemblyGAC_64System.Transactionsv4.0_4.0.0.0__b77a 5c561934e089System.Transactions.dll’. Skipped loading symbols. Module is optimized and the debugger option ‘Just My Code’ is enabled.
‘WindowsFormsApplication1.vshost.exe’ (CLR v4.0.30319: WindowsFormsApplication1.vshost.exe): Loaded ‘C:WindowsMicrosoft.NetassemblyGAC_MSILSystem.Configurationv4.0_4.0.0.0__b 03f5f7f11d50a3aSystem.Configuration.dll’. Skipped loading symbols. Module is optimized and the debugger option ‘Just My Code’ is enabled.
‘WindowsFormsApplication1.vshost.exe’ (CLR v4.0.30319: WindowsFormsApplication1.vshost.exe): Loaded ‘C:WindowsMicrosoft.NetassemblyGAC_64System.EnterpriseServicesv4.0_4.0.0.0 __b03f5f7f11d50a3aSystem.EnterpriseServices.dll’. Skipped loading symbols. Module is optimized and the debugger option ‘Just My Code’ is enabled.
‘WindowsFormsApplication1.vshost.exe’ (CLR v4.0.30319: WindowsFormsApplication1.vshost.exe): Loaded ‘C:WindowsMicrosoft.NetassemblyGAC_64System.EnterpriseServicesv4.0_4.0.0.0 __b03f5f7f11d50a3aSystem.EnterpriseServices.Wrapper.dll’. Skipped loading symbols. Module is optimized and the debugger option ‘Just My Code’ is enabled.
SQLite error (26): file is encrypted or is not a database
A first chance exception of type ‘System.Data.SQLite.SQLiteException’ occurred in System.Data.SQLite.dll
A first chance exception of type ‘System.Data.SQLite.SQLiteException’ occurred in System.Data.SQLite.dll
‘WindowsFormsApplication1.vshost.exe’ (CLR v4.0.30319: WindowsFormsApplication1.vshost.exe): Loaded ‘C:WindowsMicrosoft.NetassemblyGAC_MSILSystem.Transactions.resourcesv4.0_4 .0.0.0_ru_b77a5c561934e089System.Transactions.resources.dll’. Module was built without symbols.
System.Transactions Critical: 0 : <TraceRecord xmlns=»http://schemas.microsoft.com/2004/10/E2ETraceEvent/TraceRecord» Severity=»Critical»><TraceIdentifier>http://msdn.microsoft.com/TraceCodes/System/ActivityTracing/2004/07/Reliability/Exception/Unhandled</TraceIdentifier><Description>Необработанное исключение</Description><AppDomain>WindowsFormsApplication1.vshost.exe</AppDomain><Exception><ExceptionType>System.Data.SQLite.SQLiteException, System.Data.SQLite, Version=1.0.96.0, Culture=neutral, PublicKeyToken=db937bc2d44ff139</ExceptionType><Message>file is encrypted or is not a database
file is encrypted or is not a database</Message><StackTrace> в System.Data.SQLite.SQLite3.Prepare(SQLiteConnection cnn, String strSql, SQLiteStatement previous, UInt32 timeoutMS, String&amp; strRemain) в c:devsqlitedotnetSystem.Data.SQLiteSQLite3.cs:строка 1108
в System.Data.SQLite.SQLiteCommand.BuildNextCommand() в c:devsqlitedotnetSystem.Data.SQLiteSQLiteCommand.cs:строка 382
в System.Data.SQLite.SQLiteCommand.GetStatement(Int32 index) в c:devsqlitedotnetSystem.Data.SQLiteSQLiteCommand.cs:строка 387
в System.Data.SQLite.SQLiteDataReader.NextResult() в c:devsqlitedotnetSystem.Data.SQLiteSQLiteDataReader.cs:строка 1383
в System.Data.SQLite.SQLiteDataReader..ctor(SQLiteCommand cmd, CommandBehavior behave) в c:devsqlitedotnetSystem.Data.SQLiteSQLiteDataReader.cs:строка 123
в System.Data.SQLite.SQLiteCommand.ExecuteReader(CommandBehavior behavior) в c:devsqlitedotnetSystem.Data.SQLiteSQLiteCommand.cs:строка 858
в System.Data.SQLite.SQLiteCommand.ExecuteReader() в c:devsqlitedotnetSystem.Data.SQLiteSQLiteCommand.cs:строка 872
в WindowsFormsApplication1.Form1.proverka() в d:ПользователиМои документырабочий столDocumentsVisual Studio 2013ProjectsWindowsFormsApplication1WindowsFormsApplication1Form1.cs:строка 322
в WindowsFormsApplication1.Form1.textBox1_TextChanged(Object sender, EventArgs e) в d:ПользователиМои документырабочий столDocumentsVisual Studio 2013ProjectsWindowsFormsApplication1WindowsFormsApplication1Form1.cs:строка 360
в System.Windows.Forms.TextBoxBase.WmReflectCommand(Message&amp; m)
в System.Windows.Forms.TextBox.WndProc(Message&amp; m)
в System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)</StackTrace><ExceptionString>System.Data.SQLite.SQLiteException (0x80004005): file is encrypted or is not a database
file is encrypted or is not a database
в System.Data.SQLite.SQLite3.Prepare(SQLiteConnection cnn, String strSql, SQLiteStatement previous, UInt32 timeoutMS, String&amp; strRemain) в c:devsqlitedotnetSystem.Data.SQLiteSQLite3.cs:строка 1108
в System.Data.SQLite.SQLiteCommand.BuildNextCommand() в c:devsqlitedotnetSystem.Data.SQLiteSQLiteCommand.cs:строка 382
в System.Data.SQLite.SQLiteCommand.GetStatement(Int32 index) в c:devsqlitedotnetSystem.Data.SQLiteSQLiteCommand.cs:строка 387
в System.Data.SQLite.SQLiteDataReader.NextResult() в c:devsqlitedotnetSystem.Data.SQLiteSQLiteDataReader.cs:строка 1383
в System.Data.SQLite.SQLiteDataReader..ctor(SQLiteCommand cmd, CommandBehavior behave) в c:devsqlitedotnetSystem.Data.SQLiteSQLiteDataReader.cs:строка 123
в System.Data.SQLite.SQLiteCommand.ExecuteReader(CommandBehavior behavior) в c:devsqlitedotnetSystem.Data.SQLiteSQLiteCommand.cs:строка 858
в System.Data.SQLite.SQLiteCommand.ExecuteReader() в c:devsqlitedotnetSystem.Data.SQLiteSQLiteCommand.cs:строка 872
в WindowsFormsApplication1.Form1.proverka() в d:ПользователиМои документырабочий столDocumentsVisual Studio 2013ProjectsWindowsFormsApplication1WindowsFormsApplication1Form1.cs:строка 322
в WindowsFormsApplication1.Form1.textBox1_TextChanged(Object sender, EventArgs e) в d:ПользователиМои документырабочий столDocumentsVisual Studio 2013ProjectsWindowsFormsApplication1WindowsFormsApplication1Form1.cs:строка 360
в System.Windows.Forms.TextBoxBase.WmReflectCommand(Message&amp; m)
в System.Windows.Forms.TextBox.WndProc(Message&amp; m)
в System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)</ExceptionString></Exception></TraceRecord>
The program ‘[3120] WindowsFormsApplication1.vshost.exe’ has exited with code -1073741819 (0xc0000005) ‘Access violation’.
The program ‘[3120] WindowsFormsApplication1.vshost.exe: Program Trace’ has exited with code 0 (0x0).
Что это и что с этим делать подскажите пожалуйста?
Содержание ошибки:
Если в проекте используется SQLite, строка подключения:DataSource=Weather.db
,В Asp.NET Следующие ошибки в Core.net core SqliteException: SQLite Error 14: 'unable to open database file'
,В .Net Об ошибках можно сообщать в приложении Core Console.No Such Table 'xxx'
, Может быть вызвано тем, что относительный путь строки подключения SQLite не распознается
решение:
1. Самый простой способ — задать путь как абсолютный путь, например «C: /xx/xx/xx/Weather.db», но этому не хватает гибкости, и есть способ лучше.
два,Используйте Use .net Основной sdk, предоставляемый по умолчанию, использует шаблон проекта SQLite для создания проекта, команда выглядит следующим образом:
Создать шаблон,-au Индивидуальные средства использования аутентификации,-uld использовать локальную БД,Если параметр равен False,SQLite,Если правда,Использовать SQL Server LocalDB
dotnet new mvc -au Individual -uld false --name SQLiteCore
Относительный путь также используется в этом проектеDataSource=app.db
, Но такой ошибки нет.По сравнению с проектом, созданным VS, обнаруживается, что у startup.cs и program.cs проекта нет специальных настроек, но файл .csproj имеет еще одну конфигурацию, а именно:
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>netcoreapp2.2</TargetFramework>
<UserSecretsId>aspnet-SQLiteCore-EEF36315-16B4-44B9-AFBD-0041D5170A86</UserSecretsId>
<AspNetCoreHostingModel>InProcess</AspNetCoreHostingModel>
</PropertyGroup>
<! - Добавьте эту ItemGroup, установите значение Update для вашего собственного имени файла базы данных sqlite, и следующие значения останутся неизменными ->
<ItemGroup>
<None Update="app.db" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.App" />
<PackageReference Include="Microsoft.AspNetCore.Razor.Design" Version="2.2.0" PrivateAssets="All" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="2.2.1" />
</ItemGroup>
</Project>