Sqlite cant open error 14

SQLite error 14 can be occur from several reasons. Get the step by step guide to resolve this SQLite database error quickly without any complication.

How To Get Rid Of Sqlite Error 14?

Introduction

As the technology has brought up many changes, we have now Sqlite for managing our databases. Sqlite is server less database engine, which is attached to the end program directly. Most of the applications around us are involved with Sqlite database such as; airplanes, embedded devices, websites, etc. There is no client-server architecture maintained in Sqlite. It is self-contained and zero-configuration system and preserves data without loss since follows ACID property. Although, Sqlite works well, it shows error due to some mistakes. The errors are ‘Error Codes’ which belongs to so called ‘Result Codes’ and is of 32bit integer. Error Codes shows “something went wrong”. The 8-bit, least significant of Result Code is primary result code and the MSB is known as extended result code and provides detailed information. Sqlite error 14 is one of the error codes. Here, a detailed descriptions and its solution is discussed.

Description of Sqlite Error 14

Sqlite Error code 14 indicates SQLITE_CANTOPEN 14: Unable to open the database file.

This error occurs when the Sqlite is not able to open up the database file. The file may be a primary database or else may be on temporary disk files. Sometimes the error occurs because of inaccessibility of writing to the file for transaction.

The user may find it fishy by seeing this error. The error is wispy and does not reveal what exactly the reason is thus misleading people who end up making wrong conclusions.

The error may be because of the change in the file name or due to the corruptions in the file. Corruption can happen because of any reason, there may not be a particular reason for it.

Some of the reasons are:

  • Bug in Sqlite
  • Power failure in between the processing of transaction
  • Memory corruption
  • Operating system might have crashed
  • The application might not have shut down properly
  • Disk/Flash memory failure
  • Application might have crashed

In PHP, error can be seen as:

SQLSTATE: General error: 14 unable to open database file.

How To Overcome the Error “unable to open database” ?

To get rid of the error, user might have to change the settings in the directory where database is stored. The following command will be useful:

Sqlite File Path

Conclusion

However, the manual changes made to the directory won’t be sufficient sometimes. You may need the assistance of another hand-software. Sqlite Viewer can be helpful to overcome the Sqlite Error 14 and the user may find it even interesting, as it gets rid of the corruption caused to the database files.

Содержание

  1. How To Get Rid Of Sqlite Error 14?
  2. Introduction
  3. Description of Sqlite Error 14
  4. How To Overcome the Error “unable to open database” ?
  5. Conclusion
  6. SQLite error 14: unable to open database file #415
  7. Comments
  8. What did you do?
  9. What did you expect to happen?
  10. What happened instead?
  11. Demo Project
  12. SQLITE_CANTOPEN: unable to open database file #304
  13. Comments
  14. Footer
  15. Sqlite3, OperationalError: невозможно открыть файл базы данных
  16. 19 ответы

How To Get Rid Of Sqlite Error 14?

Introduction

As the technology has brought up many changes, we have now Sqlite for managing our databases. Sqlite is server less database engine, which is attached to the end program directly. Most of the applications around us are involved with Sqlite database such as; airplanes, embedded devices, websites, etc. There is no client-server architecture maintained in Sqlite. It is self-contained and zero-configuration system and preserves data without loss since follows ACID property. Although, Sqlite works well, it shows error due to some mistakes. The errors are ‘Error Codes’ which belongs to so called ‘Result Codes’ and is of 32bit integer. Error Codes shows “something went wrong”. The 8-bit, least significant of Result Code is primary result code and the MSB is known as extended result code and provides detailed information. Sqlite error 14 is one of the error codes. Here, a detailed descriptions and its solution is discussed.

Description of Sqlite Error 14

Sqlite Error code 14 indicates SQLITE_CANTOPEN 14: Unable to open the database file.

This error occurs when the Sqlite is not able to open up the database file. The file may be a primary database or else may be on temporary disk files. Sometimes the error occurs because of inaccessibility of writing to the file for transaction.

The user may find it fishy by seeing this error. The error is wispy and does not reveal what exactly the reason is thus misleading people who end up making wrong conclusions.

The error may be because of the change in the file name or due to the corruptions in the file. Corruption can happen because of any reason, there may not be a particular reason for it.

Some of the reasons are:

  • Bug in Sqlite
  • Power failure in between the processing of transaction
  • Memory corruption
  • Operating system might have crashed
  • The application might not have shut down properly
  • Disk/Flash memory failure
  • Application might have crashed

In PHP, error can be seen as:

SQLSTATE: General error: 14 unable to open database file.

How To Overcome the Error “unable to open database” ?

To get rid of the error, user might have to change the settings in the directory where database is stored. The following command will be useful:

Conclusion

However, the manual changes made to the directory won’t be sufficient sometimes. You may need the assistance of another hand-software. Sqlite Viewer can be helpful to overcome the Sqlite Error 14 and the user may find it even interesting, as it gets rid of the corruption caused to the database files.

Disclaimer : – © 2023 Sqlite Viewer is an independent provider of Sqlite products & services. Sqlite Viewer is not in affiliation with any of the third–party organizations unless it is expressed explicitly. Read More.

Источник

SQLite error 14: unable to open database file #415

What did you do?

I wanted to connect my pre-loaded sqlite database and bundled it within the Xcode project navigator.

What did you expect to happen?

I wanted to connect that database. I already have successful connection with simulator but no luck with real iPhone.

What happened instead?

I get this error:

2018-09-22 19:01:42.098199+0800 myWay[1069:233261] [logging-persist] cannot open file at line 42249 of [95fbac39ba]
2018-09-22 19:01:42.098231+0800 myWay[1069:233261] [logging-persist] os_unix.c:42249: (0) open(/var/containers/Bundle/Application/B93852F8-F874-445F-911C-624CEDD765C3/myWay.app/db2.sqlite-wal) — Undefined error: 0
2018-09-22 19:01:42.098246+0800 myWay[1069:233261] [logging-persist] unable to open database file
SQLite error 14: unable to open database file

Demo Project

The text was updated successfully, but these errors were encountered:

Error code 14 stands for SQLITE_CANTOPEN, «unable to open database file». I don’t know why SQLite is unable to open your database. But did you check, for example, that there exists a database file at the path you provide?

In the simulator everything works perfectly. I think i need to copy that sqlite file right ?
How can i copy that sqlite file to iPhone’s path folder ? Is there a way to do it with FileManager.copyItems(at: to:) ?

What path are you currently using? The one that works on the simulator, but fails on the device?

This looks correct. Now make sure that all those sentences below are true. Do check them, don’t simply assume they are true:

  • you have a db2.sqlite resource in your project.
  • you made sure that this resource is bundled in your application, on the device.
  • you initialize a DatabaseQueue object only once in the lifetime of your application.
  • the format of the db2.sqlite file is compatible with the version of SQLite that ships with the iOS version on your device.

If you still have error SQLITE_CANTOPEN after those checks, then I really don’t know what is happening.

Also, since the log you provide in the initial comment contains db2.sqlite-wal , I conclude that your database is not a simple db2.sqlite file. It has been opened in the WAL mode at some point.

Do you also use DatabasePool? Don’t mix DatabaseQueue and DatabasePool. Choose one. And create one in the lifetime of your application.

Do you attempt at modifying the content of the database? You can not do that if the database is bundled as a resource, because resources can not be modified by the application. To make sure the database resource is not modified, open the database in the read-only mode:

And look at the FAQ, especially How do I open a database stored as a resource of my application?

Yes i edited the SQL file that is correct.
I will let you know with updates

I edited my code like this. Still getting same error

I changed this line
let dbQueue = try DatabaseQueue(path: dbPath, configuration: config) with this
let dbQueue = try DatabaseQueue(path: dbPath)
Now it is working !!

Great! I don’t quite know what happened, but what counts is that your app can run. Happy GRDB!

Источник

SQLITE_CANTOPEN: unable to open database file #304

Node v8.3.0
NPM v5.3.0
pkg@4.3.0-beta.1

Im using sqlite3 package for node, trying to access my db file:

I know the file is there as it can be reached by fs, here is the output from console.logs:

And the sqlite3 error:

Error: SQLITE_CANTOPEN: unable to open database file

The text was updated successfully, but these errors were encountered:

@colinmcparland how did you resolve the issue

edit: fixed — my issue was that i used path.resolve(__dirname, filename) to locate my db files

meet the same issue, any one can help?

had this for months, any solution?

I’m also having this same issue. Is there a reason why it’s closed?

Tried with and without path.resolve() (and path.normalize() etc.). all get same same issue:
file exists
but sqlite via nodejs gets the SQLITE_CANTOPEN error as described here.

I’ve set READONLY on the db, since I’m pretty sure it won’t be writable since code isn’t in /tmp and underlying Lambda isn’t writable.

Could very will be missing something, but tried a bunch.

check your (resolved) path (ex. log it)
mine pointed after packaging to a pkg internal path

I had this issue also and resolved it by creating directory «database» in my project directory.

var db = new sqlite3.Database( path.resolve(__dirname, ‘db.sqlite’) );

Hi folks! I’m also facing the same issue. Some times it works fine with my current configuration.
This is my knex configuration.

development: <
client: ‘sqlite3’,
connection: <
filename: ‘./src/database/db.sqlite’
>
>,
.

This is my connection file:

const knex = require(‘knex’);
const configuration = require(‘../../knexfile’);
const connection = knex(configuration.development);
module.exports = connection;

The only way I found to solve the this issue is to delete the src/database/db.sqlite and create the db.sqlite again in the same path

Thankfully after a tone of research I found the issue. To solve we have to use the absolute path on the database path like the following script:

development: <
client: ‘sqlite3’,
connection: <
filename: ‘/absolutepath/db.sqlite’
>

Thanks! was having the same problem. @sousadgaspar

Cara muito obrigado @sousadgaspar

filename: ‘dir_name/db.sqlite’,
//just leave out the first /

Maybe this means nothing, I don’t know I’m a beginner at node. I ran a tutorial on http://localhost:3000/ which worked fine. Some while later tried to require(‘sqlite3’) in an existing project using http://localhost:8080/ and ended up here after staring at the same error.

Reopening the tutorial worked. The page says
Please enter ‘http://localhost:3000/close’ to close the database connection before closing this window
Enter that in Firefox devtools and suddenly I have working sqlite3 on 8080.

Node is running in WSL on Windows 11; the machine has been rebooted a dozen times in the interim. I can now run both servers in different browser tabs, so it doen’t really add up but I’ll leave this here just in case it helps someone.

edit: fixed — my issue was that i used path.resolve(__dirname, filename) to locate my db files

how to resolve the error

I had the same issue. In my case i just needed to clean my database file because i already had a «database.sqlite» named folder. This error is related to problems on the folder structure / path

© 2023 GitHub, Inc.

You can’t perform that action at this time.

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.

Источник

Sqlite3, OperationalError: невозможно открыть файл базы данных

Вопрос: Почему я не могу открыть базу данных?

Информация: я работаю над проектом, использующим sqlite3 база данных. Я написал тестовую программу, которая запускается и передает ей базу данных:

Программа модульного тестирования может сделать db без каких-либо проблем. Но когда я действительно использую программу, передающую ей то же место, я получил ошибку ниже:

OperationalError: невозможно открыть файл базы данных

Я пробовал делать это с помощью:

В трех случаях я получил указанную выше ошибку. Самое неприятное — это то, что unittest может делать это нормально, но настоящая программа не может.

Есть какие-нибудь подсказки относительно того, что, черт возьми, происходит?

Это полный путь? Вы уверены, что не передаете путь через переменные среды или

или какая-то другая короткая форма? — chrisaycock

Каталог / tmp / cer / существует? — thkala

@chrisaycook: да. Я не. @thkala: это так. — Narcolapser

19 ответы

Первичный диагноз: SQLite по какой-то причине не может открыть этот файл.

Проверка очевидных причин, почему, и в примерном порядке, в котором я рекомендую проверять:

  • Программа работает на той же машине, на которой вы ее тестируете?
  • Он работает от имени вас (или, по крайней мере, от того же пользователя, которым вы его тестируете)?
  • Диск содержит /tmp полный? (Вы используете Unix, поэтому используйте df /tmp выяснить.)
  • Ли /tmp/cer каталог имеет «нечетные» разрешения? (SQLite должен иметь возможность создавать в нем дополнительные файлы, чтобы обрабатывать такие вещи, как журнал фиксации.)
  • Использует ли код модульного теста эту базу данных? (Параллельно открывается Он возможно с достаточно современным SQLite и в правильной файловой системе — хотя /tmp практически всегда находится в нужном виде файловой системы, так что, вероятно, это не так — но все же не рекомендуется.)
  • Код разработки на самом деле пытаетесь записать в эту базу данных, или что-то «умное» поймает вас и заставит попытаться открыть что-то еще? (Раньше я попадал в ловушку этого кода в моем коде; не думайте, что с вами такого не может случиться . )
  • Используете ли вы одну и ту же версию библиотеки SQLite в модульных тестах и ​​производственном коде?

Если вы не на одном компьютере, вполне возможно, что в производственной системе нет /tmp/cer каталог. Очевидно, что сначала нужно это исправить. Точно так же, если вы работаете на одном компьютере, но работаете как разные пользователи, у вас, вероятно, возникнут проблемы с разрешениями / владением. Дисковое пространство — еще одна серьезная проблема, но менее вероятная. Я не думаю, что это последние три, но стоит проверить, решены ли более очевидные проблемы развертывания. Если ничего из вышеперечисленного нет, вы столкнулись с экзотической проблемой и должны будете сообщить гораздо больше информации (это может быть даже ошибка в SQLite, но, зная разработчиков, я считаю, что это маловероятно).

да. да. нет. не то, что я знаю из. Не должно быть. нет. база данных создана той же системой, с той лишь разницей, что UTFile.py вызывает ее вместо cSystem.py. да, я использую встроенную версию SQLite, которая поставляется с python. — Наркозависимый

нашел свою проблему. струны не были полностью идентичны. Была небольшая разница из-за моего файла конфигурации. файл конфигурации оставлял разрыв строки на моем пути, поэтому я пытался открыть: ‘/tmp/cer/ncloud.db’, была моя проблема. но это был очень хороший ответ. спасибо вам любезно! — Наркозависимый

Спасибо! У меня была эта проблема, и пользователю действительно не хватало прав на запись в каталог для пользователя веб-сервера, хотя у файла были права на запись для этого пользователя. — арантий

У меня такая же проблема. Хотя база данных имеет разрешение 777, каталог, в котором она находился, был 755, изменение этого значения на 777 также решило проблему. Ваш отзыв о «лишних разрешениях» мне поможет. — дядя

У меня такая же проблема, но в контейнере докеров, как мне это сделать? — Мвибуца Флориберт

Это сработало для меня:

Примечание: двойные косые черты в полном пути

. Python v2.7 на Win 7 Enterprise и Win Xp Pro

Надеюсь, это поможет кому-то.

ответ дан 31 окт ’12, 19:10

на ubuntu также помогли обратные косые черты: create_engine(«sqlite:///datadb_folderexample.db») — Зефро

В unix я получил эту ошибку при использовании

ярлык для каталога пользователя. Изменив его на /home/user разрешил ошибку.

Создан 11 июля ’17, 17:07

То же самое и здесь, хотя я хотел бы знать, почему это имеет смысл. Sqlite не позволяет использовать

в качестве домашней ссылки? — Серхио Лусеро

Одна из причин может заключаться в запуске кода по пути, который не совпадает с указанным вами путем для базы данных. Например, если в вашем коде есть:

И вы запускаете код внутри folder_A или в других местах, где нет folder_A это вызовет такую ​​ошибку. Причина в том, что SQLite создаст файл базы данных, если он не существует, а не папка.

Еще один способ обойти эту проблему — заключить команду подключения в try-except выражение и создание каталога, если оно вызывает sqlite3.OperationalError .

из ОС импортировать mkdir импортировать sqlite3 как облегченный

Спасибо! Это то, что я искал. Более того, разве не else здесь избыточно, так как conn объект всегда создается всякий раз, когда срабатывает предложение? Кроме того, не было бы более идиоматичным переместить оператор в else пункт к except часть и добавить finally с conn.close() ? — Кшитидж Сараоги

Да, спасибо за заметку. Часть «else» на самом деле должна быть «finally». Также нет необходимости закрывать соединение сразу после его создания. — касравнд

это именно то, с чем я столкнулся, и я должен был это поймать . — Джефф Блюмел

Я столкнулся с той же проблемой в Windows 7. Имя моей базы данных было test и я получил ошибку:

Я заменил test с test.db и все прошло гладко.

ответ дан 14 дек ’13, 15:12

В моем случае решение заключалось в использовании абсолютного пути для поиска существующего файла:

Я не знаю, почему это исправление работает: путь содержал только символы ASCII без пробелов. Тем не менее, это имело значение.

Для справки: Windows 7, Python 3.6.5 (64-бит).

Мне не удалось воспроизвести проблему на другом компьютере (также с Windows 7, 3.6.4-разрядная версия Python 64), поэтому я понятия не имею, почему это исправление работает.

ответ дан 15 апр.

У меня была такая же проблема, и оказалось, что мой ноутбук работал из папки, смежной с моей базой данных (например, источник> записные книжки и источник> db> database.db). Абсолютный путь решил это. — Alofgran

Это определенно проблема с разрешениями. Если кто-то получает эту ошибку в Linux, убедитесь, что вы запускаете команду с sudo поскольку файл, скорее всего, принадлежит пользователю root. Надеюсь, это поможет!

Источник

Содержание

  1. How To Get Rid Of Sqlite Error 14?
  2. Introduction
  3. Description of Sqlite Error 14
  4. How To Overcome the Error “unable to open database” ?
  5. Conclusion
  6. Code 14: Unable to open database
  7. SQLite Error 14: ‘unable to open database file’ using Azure AppServices Linux and WEBSITES_ENABLE_APP_SERVICE_STORAGE=true #19536
  8. Comments
  9. WernerMairl commented Jan 9, 2020
  10. Microsoft.Data.Sqlite.SqliteException: ‘SQLite Error 14: ‘unable to open database file’.’ #3819
  11. Comments
  12. stefanolson commented Oct 18, 2019
  13. Steps to Reproduce
  14. Expected Behavior
  15. Actual Behavior
  16. Version Information
  17. Log File

How To Get Rid Of Sqlite Error 14?

Introduction

As the technology has brought up many changes, we have now Sqlite for managing our databases. Sqlite is server less database engine, which is attached to the end program directly. Most of the applications around us are involved with Sqlite database such as; airplanes, embedded devices, websites, etc. There is no client-server architecture maintained in Sqlite. It is self-contained and zero-configuration system and preserves data without loss since follows ACID property. Although, Sqlite works well, it shows error due to some mistakes. The errors are ‘Error Codes’ which belongs to so called ‘Result Codes’ and is of 32bit integer. Error Codes shows “something went wrong”. The 8-bit, least significant of Result Code is primary result code and the MSB is known as extended result code and provides detailed information. Sqlite error 14 is one of the error codes. Here, a detailed descriptions and its solution is discussed.

Description of Sqlite Error 14

Sqlite Error code 14 indicates SQLITE_CANTOPEN 14: Unable to open the database file.

This error occurs when the Sqlite is not able to open up the database file. The file may be a primary database or else may be on temporary disk files. Sometimes the error occurs because of inaccessibility of writing to the file for transaction.

The user may find it fishy by seeing this error. The error is wispy and does not reveal what exactly the reason is thus misleading people who end up making wrong conclusions.

The error may be because of the change in the file name or due to the corruptions in the file. Corruption can happen because of any reason, there may not be a particular reason for it.

Some of the reasons are:

  • Bug in Sqlite
  • Power failure in between the processing of transaction
  • Memory corruption
  • Operating system might have crashed
  • The application might not have shut down properly
  • Disk/Flash memory failure
  • Application might have crashed

In PHP, error can be seen as:

SQLSTATE: General error: 14 unable to open database file.

How To Overcome the Error “unable to open database” ?

To get rid of the error, user might have to change the settings in the directory where database is stored. The following command will be useful:

Conclusion

However, the manual changes made to the directory won’t be sufficient sometimes. You may need the assistance of another hand-software. Sqlite Viewer can be helpful to overcome the Sqlite Error 14 and the user may find it even interesting, as it gets rid of the corruption caused to the database files.

Disclaimer : – © 2022 Sqlite Viewer is an independent provider of Sqlite products & services. Sqlite Viewer is not in affiliation with any of the third–party organizations unless it is expressed explicitly. Read More.

Источник

Code 14: Unable to open database

I know this question has been asked before. But, the problem is, the same code (for database handler) is working for another app, but not the one I’m currently working on. I’ve even made sure the permissions are given by checking the permissions in settings. Here’s the logcat:

05-13 15:35:45.693 29696-29696/com.example.hack.corrector E/SQLiteLog: (14) cannot open file at line 31282 of [5a3022e081] (14) os_unix.c:31282: (21) open(/data/user/0/com.example.hack.corrector/databases/) — 05-13 15:35:45.694 29696-29696/com.example.hack.corrector E/SQLiteDatabase: Failed to open database ‘/data/user/0/com.example.hack.corrector/databases/’. android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open database at android.database.sqlite.SQLiteConnection.nativeOpen(Native Method) at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:207) at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:191) at android.database.sqlite.SQLiteConnectionPool.openConnectionLocked(SQLiteConnectionPool.java:463) at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:185) at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:177) at android.database.sqlite.SQLiteDatabase.openInner(SQLiteDatabase.java:806) at android.database.sqlite.SQLiteDatabase.open(SQLiteDatabase.java:791) at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:694) at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:669) at com.example.hakc.corrector.VocabDatabase.openDataBase(VocabDatabase.java:127) at com.example.hakc.corrector.scrapeservice.createDB(scrapeservice.java:31) at com.example.hakc.corrector.scrapeservice.onStartCommand(scrapeservice.java:23) at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:3049) at android.app.ActivityThread.access$2300(ActivityThread.java:154) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1479) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:157) at android.app.ActivityThread.main(ActivityThread.java:5571) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:745) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:635)

and here’s the database handler code:

I’ve checked the file explorer and the database has been copied and in place. But still, the error is occurring. I’ve never had problem with the other application that was implementing the same database handler code (Vocabdatabase). I’ve spent one and half a day trying to solve this problem but nothing is working.

Источник

SQLite Error 14: ‘unable to open database file’ using Azure AppServices Linux and WEBSITES_ENABLE_APP_SERVICE_STORAGE=true #19536

I have a asp net core app using ef core and Sqlite!
Everything in the latest released dotnet core 3.1 versions.

Hosting is up and running as Azure Web App Linux (docker) container
(base container: mcr.microsoft.com/dotnet/core/aspnet:3.1)

The app is configured to use a sqlite file on ‘/home/data/task365.sqlite’

using ‘WEBSITES_ENABLE_APP_SERVICE_STORAGE=false» everything woks fine:

  • directory «data» is created if does not exists
  • migrations are executed
  • ef-context is working

if we change the setting to

then we are not able to start the app anymore!
this setting basically means that a volume is mapped to «/home».

Exception message/stack trace:
An error occurred using the connection to database ‘main’ on server ‘/home/data/task365.sqlite’.
2020-01-09T06:27:17.714552777Z Application startup exception: Microsoft.Data.Sqlite.SqliteException (0x80004005): SQLite Error 14: ‘unable to open database file’.
2020-01-09T06:27:17.714586977Z at Microsoft.Data.Sqlite.SqliteException.ThrowExceptionForRC(Int32 rc, sqlite3 db)

After a lot of investigations i must assume that the problem is caused by using a mounted path.
I see the same symptoms if i’m using the volume mapping feature in Azure Web Apps for Linux instead of ‘WEBSITES_ENABLE_APP_SERVICE_STORAGE’.

What i have verified:
my process has write access to the mounted folder — File.Copy or File.Move to the mounted folder is working!

There are some known restrictions for (linux) mounted volumes in general or Azure App Service Mounts ?

I have found (via google) the following item that means
«Unfortunately, Sqlite is not supported on App Service on Linux.»
but without any background information.

The text was updated successfully, but these errors were encountered:

Источник

Microsoft.Data.Sqlite.SqliteException: ‘SQLite Error 14: ‘unable to open database file’.’ #3819

I’m not really sure if this is an entity framework issue or a Xamarin issue. But the same code, same dll (.net standard) works perfectly fine on Windows desktop so I’m assuming is related to Xamarin. This code worked fine the last time I built it for Xamarin a few months ago.

Steps to Reproduce

When I run my application and call this line:
Database.EnsureCreated();

I get this exception:
Microsoft.Data.Sqlite.SqliteException: ‘SQLite Error 14: ‘unable to open database file’.’

I have tried various different file name options, but this is the last I’ve tested:
optionsBuilder.UseSqlite($»Data Source=test.db»);

I’ve tried to remove EF core from all the libraries involved. Started out using EF core 2.26 (which I need to go back to), but tested EF core 3.0. Same problem. And upgraded to all the latest Xamarin nuget packages.

If I look back in the debug window I see this:
10-18 23:17:50.959 D/Mono (22379): Assembly Ref addref Microsoft.EntityFrameworkCore.Relational[0x712b9db700] -> System.Diagnostics.DiagnosticSource[0x713b7cc700]: 3
10-18 23:17:50.963 D/Mono (22379): Assembly Loader probing location: ‘/Users/builder/jenkins/workspace/archive-mono/2019-08/android/release/sdks/out/android-arm64-v8a-release/lib/Microsoft.EntityFrameworkCore.Relational.resources.dll’.
10-18 23:17:50.963 D/Mono (22379): Assembly Loader probing location: ‘//Facades/Microsoft.EntityFrameworkCore.Relational.resources.dll’.
10-18 23:17:50.963 D/Mono (22379): Assembly Loader probing location: ‘/Users/builder/jenkins/workspace/archive-mono/2019-08/android/release/sdks/out/android-arm64-v8a-release/lib/Microsoft.EntityFrameworkCore.Relational.resources.exe’.
10-18 23:17:50.963 D/Mono (22379): Assembly Loader probing location: ‘//Facades/Microsoft.EntityFrameworkCore.Relational.resources.exe’.
10-18 23:17:50.963 D/Mono (22379): Assembly Loader probing location: ‘/storage/emulated/0/Android/data/com.companyname.FmXamarin/files/.override/en-NZ/Microsoft.EntityFrameworkCore.Relational.resources.dll’.
10-18 23:17:51.321 D/Mono (22379): Assembly Loader probing location: ‘/Users/builder/jenkins/workspace/archive-mono/2019-08/android/release/sdks/out/android-arm64-v8a-release/lib/Microsoft.EntityFrameworkCore.Relational.resources.dll’.
10-18 23:17:51.322 D/Mono (22379): Assembly Loader probing location: ‘//Facades/Microsoft.EntityFrameworkCore.Relational.resources.dll’.
10-18 23:17:51.322 D/Mono (22379): Assembly Loader probing location: ‘/Users/builder/jenkins/workspace/archive-mono/2019-08/android/release/sdks/out/android-arm64-v8a-release/lib/Microsoft.EntityFrameworkCore.Relational.resources.exe’.
10-18 23:17:51.323 D/Mono (22379): Assembly Loader probing location: ‘//Facades/Microsoft.EntityFrameworkCore.Relational.resources.exe’.
10-18 23:17:51.323 D/Mono (22379): Assembly Loader probing location: ‘/storage/emulated/0/Android/data/com.companyname.FmXamarin/files/.override/en/Microsoft.EntityFrameworkCore.Relational.resources.dll’.
10-18 23:17:51.476 D/Mono (22379): DllImport searching in: ‘e_sqlite3’ (‘libe_sqlite3.so’).
10-18 23:17:51.476 D/Mono (22379): Searching for ‘sqlite3_open_v2’.
10-18 23:17:51.480 D/Mono (22379): DllImport searching in: ‘e_sqlite3’ (‘libe_sqlite3.so’).
10-18 23:17:51.480 D/Mono (22379): Searching for ‘sqlite3_errcode’.
10-18 23:17:51.482 D/Mono (22379): DllImport searching in: ‘e_sqlite3’ (‘libe_sqlite3.so’).
10-18 23:17:51.482 D/Mono (22379): Searching for ‘sqlite3_errmsg’.
10-18 23:17:51.484 D/Mono (22379): DllImport searching in: ‘e_sqlite3’ (‘libe_sqlite3.so’).
10-18 23:17:51.485 D/Mono (22379): Searching for ‘sqlite3_extended_errcode’.
10-18 23:17:51.488 D/Mono (22379): Assembly Loader probing location: ‘/Users/builder/jenkins/workspace/archive-mono/2019-08/android/release/sdks/out/android-arm64-v8a-release/lib/Microsoft.Data.Sqlite.resources.dll’.
10-18 23:17:51.488 D/Mono (22379): Assembly Loader probing location: ‘//Facades/Microsoft.Data.Sqlite.resources.dll’.
10-18 23:17:51.488 D/Mono (22379): Assembly Loader probing location: ‘/Users/builder/jenkins/workspace/archive-mono/2019-08/android/release/sdks/out/android-arm64-v8a-release/lib/Microsoft.Data.Sqlite.resources.exe’.
10-18 23:17:51.488 D/Mono (22379): Assembly Loader probing location: ‘//Facades/Microsoft.Data.Sqlite.resources.exe’.
10-18 23:17:51.489 D/Mono (22379): Assembly Loader probing location: ‘/storage/emulated/0/Android/data/com.companyname.FmXamarin/files/.override/en-NZ/Microsoft.Data.Sqlite.resources.dll’.
10-18 23:17:51.694 D/Mono (22379): Assembly Loader probing location: ‘/Users/builder/jenkins/workspace/archive-mono/2019-08/android/release/sdks/out/android-arm64-v8a-release/lib/Microsoft.Data.Sqlite.resources.dll’.
10-18 23:17:51.694 D/Mono (22379): Assembly Loader probing location: ‘//Facades/Microsoft.Data.Sqlite.resources.dll’.
10-18 23:17:51.694 D/Mono (22379): Assembly Loader probing location: ‘/Users/builder/jenkins/workspace/archive-mono/2019-08/android/release/sdks/out/android-arm64-v8a-release/lib/Microsoft.Data.Sqlite.resources.exe’.
10-18 23:17:51.695 D/Mono (22379): Assembly Loader probing location: ‘//Facades/Microsoft.Data.Sqlite.resources.exe’.
10-18 23:17:51.695 D/Mono (22379): Assembly Loader probing location: ‘/storage/emulated/0/Android/data/com.companyname.FmXamarin/files/.override/en/Microsoft.Data.Sqlite.resources.dll’.
Microsoft.Data.Sqlite.SqliteException: ‘SQLite Error 14: ‘unable to open database file’.’

Expected Behavior

Should open the database file, like it used to

Actual Behavior

Version Information

Microsoft Visual Studio Community 2019 Preview
Version 16.4.0 Preview 2.0
VisualStudio.16.Preview/16.4.0-pre.2.0+29411.138
Microsoft .NET Framework
Version 4.8.03752

Installed Version: Community

Visual C++ 2019 00435-60000-00000-AA532
Microsoft Visual C++ 2019

ADL Tools Service Provider 1.0
This package contains services used by Data Lake tools

ASP.NET and Web Tools 2019 16.4.284.46185
ASP.NET and Web Tools 2019

ASP.NET Web Frameworks and Tools 2019 16.4.284.46185
For additional information, visit https://www.asp.net/

AssemblyInfo Wizard 1.0
AssemblyInfo Wizard

Azure App Service Tools v3.0.0 16.4.284.46185
Azure App Service Tools v3.0.0

Azure Data Lake Node 1.0
This package contains the Data Lake integration nodes for Server Explorer.

Azure Data Lake Tools for Visual Studio 2.4.1000.0
Microsoft Azure Data Lake Tools for Visual Studio

Azure Functions and Web Jobs Tools 16.4.284.46185
Azure Functions and Web Jobs Tools

Azure Stream Analytics Tools for Visual Studio 2.4.1000.0
Microsoft Azure Stream Analytics Tools for Visual Studio

C# Tools 3.4.0-beta2-19504-06+154af84a603094b52bd08b3366c4448f7481af52
C# components used in the IDE. Depending on your project type and settings, a different version of the compiler may be used.

Common Azure Tools 1.10
Provides common services for use by Azure Mobile Services and Microsoft Azure Tools.

Extensibility Message Bus 1.2.0 (d16-2@8b56e20)
Provides common messaging-based MEF services for loosely coupled Visual Studio extension components communication and integration.

Fabric.DiagnosticEvents 1.0
Fabric Diagnostic Events

IntelliCode Extension 1.0
IntelliCode Visual Studio Extension Detailed Info

Microsoft Azure HDInsight Azure Node 2.4.1000.0
HDInsight Node under Azure Node

Microsoft Azure Hive Query Language Service 2.4.1000.0
Language service for Hive query

Microsoft Azure Service Fabric Tools for Visual Studio 16.0
Microsoft Azure Service Fabric Tools for Visual Studio

Microsoft Azure Stream Analytics Language Service 2.4.1000.0
Language service for Azure Stream Analytics

Microsoft Azure Stream Analytics Node 1.0
Azure Stream Analytics Node under Azure Node

Microsoft Azure Tools 2.9
Microsoft Azure Tools for Microsoft Visual Studio 0x10 — v2.9.20905.5

Microsoft Continuous Delivery Tools for Visual Studio 0.4
Simplifying the configuration of Azure DevOps pipelines from within the Visual Studio IDE.

Microsoft JVM Debugger 1.0
Provides support for connecting the Visual Studio debugger to JDWP compatible Java Virtual Machines

Microsoft Library Manager 2.0.87+gbb515bf382
Install client-side libraries easily to any web project

Microsoft MI-Based Debugger 1.0
Provides support for connecting Visual Studio to MI compatible debuggers

Microsoft Visual C++ Wizards 1.0
Microsoft Visual C++ Wizards

Microsoft Visual Studio Tools for Containers 1.1
Develop, run, validate your ASP.NET Core applications in the target environment. F5 your application directly into a container with debugging, or CTRL + F5 to edit & refresh your app without having to rebuild the container.

Microsoft Visual Studio VC Package 1.0
Microsoft Visual Studio VC Package

Mono Debugging for Visual Studio 16.5.21 (2604ba1)
Support for debugging Mono processes with Visual Studio.

NuGet Package Manager 5.4.0
NuGet Package Manager in Visual Studio. For more information about NuGet, visit https://docs.nuget.org/

Office Developer Tools for Visual Studio 16.0.29319.00
Microsoft Office Developer Tools for Visual Studio

ProjectServicesPackage Extension 1.0
ProjectServicesPackage Visual Studio Extension Detailed Info

SQL Server Data Tools 16.0.61910.04130
Microsoft SQL Server Data Tools

ToolWindowHostedEditor 1.0
Hosting json editor into a tool window

TypeScript Tools 16.0.10926.2001
TypeScript Tools for Microsoft Visual Studio

Visual Basic Tools 3.4.0-beta2-19504-06+154af84a603094b52bd08b3366c4448f7481af52
Visual Basic components used in the IDE. Depending on your project type and settings, a different version of the compiler may be used.

Visual F# Tools 10.4 for F# 4.6 16.4.0-beta.19504.1+e3676d75d501a2df6789ad0f5ebc310bc2cee6b5
Microsoft Visual F# Tools 10.4 for F# 4.6

Visual Studio Code Debug Adapter Host Package 1.0
Interop layer for hosting Visual Studio Code debug adapters in Visual Studio

Visual Studio Container Tools Extensions (Preview) 1.0
View, manage, and diagnose containers within Visual Studio.

Visual Studio Tools for Containers 1.0
Visual Studio Tools for Containers

Visual Studio Tools for Kubernetes 1.0
Visual Studio Tools for Kubernetes

VisualStudio.DeviceLog 1.0
Information about my package

VisualStudio.Foo 1.0
Information about my package

VisualStudio.Mac 1.0
Mac Extension for Visual Studio

Workflow Manager Tools 1.0 1.0
This package contains the necessary Visual Studio integration components for Workflow Manager.

Xamarin 16.4.000.269 (d16-4@9202c30)
Visual Studio extension to enable development for Xamarin.iOS and Xamarin.Android.

Xamarin Designer 16.4.0.289 (remotes/origin/d16-4@e3c99110c)
Visual Studio extension to enable Xamarin Designer tools in Visual Studio.

Xamarin Templates 16.4.15 (51cdaa7)
Templates for building iOS, Android, and Windows apps with Xamarin and Xamarin.Forms.

Xamarin.iOS and Xamarin.Mac SDK 13.8.1.1 (2e360ee)
Xamarin.iOS and Xamarin.Mac Reference Assemblies and MSBuild support.

Log File

——— beginning of crash
10-18 06:44:55.643 19876 19876 E AndroidRuntime: FATAL EXCEPTION: main
10-18 06:44:55.643 19876 19876 E AndroidRuntime: Process: kodo.app.mymaccasreview, PID: 19876
10-18 06:44:55.643 19876 19876 E AndroidRuntime: java.lang.RuntimeException: Unable to start receiver com.onesignal.BootUpReceiver: java.lang.IllegalStateException: Not allowed to start service Intent < cmp=kodo.app.mymaccasreview/com.onesignal.NotificationRestoreService (has extras) >: app is in background uid UidRecord<14e4da5 u0a290 rcvr idle change:uncached procs:1 proclist:19876, seq(0,0,0)>
10-18 06:44:55.643 19876 19876 E AndroidRuntime: at android.app.ActivityThread.handleReceiver(ActivityThread.java:3590)
10-18 06:44:55.643 19876 19876 E AndroidRuntime: at android.app.ActivityThread.access$1300(ActivityThread.java:235)
10-18 06:44:55.643 19876 19876 E AndroidRuntime: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1779)
10-18 06:44:55.643 19876 19876 E AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:106)
10-18 06:44:55.643 19876 19876 E AndroidRuntime: at android.os.Looper.loop(Looper.java:214)
10-18 06:44:55.643 19876 19876 E AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:6986)
10-18 06:44:55.643 19876 19876 E AndroidRuntime: at java.lang.reflect.Method.invoke(Native Method)
10-18 06:44:55.643 19876 19876 E AndroidRuntime: at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
10-18 06:44:55.643 19876 19876 E AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1445)
10-18 06:44:55.643 19876 19876 E AndroidRuntime: Caused by: java.lang.IllegalStateException: Not allowed to start service Intent < cmp=kodo.app.mymaccasreview/com.onesignal.NotificationRestoreService (has extras) >: app is in background uid UidRecord<14e4da5 u0a290 rcvr idle change:uncached procs:1 proclist:19876, seq(0,0,0)>
10-18 06:44:55.643 19876 19876 E AndroidRuntime: at android.app.ContextImpl.startServiceCommon(ContextImpl.java:1666)
10-18 06:44:55.643 19876 19876 E AndroidRuntime: at android.app.ContextImpl.startService(ContextImpl.java:1611)
10-18 06:44:55.643 19876 19876 E AndroidRuntime: at android.content.ContextWrapper.startService(ContextWrapper.java:677)
10-18 06:44:55.643 19876 19876 E AndroidRuntime: at android.content.ContextWrapper.startService(ContextWrapper.java:677)
10-18 06:44:55.643 19876 19876 E AndroidRuntime: at android.support.v4.content.WakefulBroadcastReceiver.startWakefulService(WakefulBroadcastReceiver.java:99)
10-18 06:44:55.643 19876 19876 E AndroidRuntime: at com.onesignal.BootUpReceiver.onReceive(BootUpReceiver.java:42)
10-18 06:44:55.643 19876 19876 E AndroidRuntime: at android.app.ActivityThread.handleReceiver(ActivityThread.java:3581)
10-18 06:44:55.643 19876 19876 E AndroidRuntime: . 8 more
10-18 21:59:28.072 26920 26920 E AndroidRuntime: FATAL EXCEPTION: main
10-18 21:59:28.072 26920 26920 E AndroidRuntime: Process: com.companyname.FmXamarin, PID: 26920
10-18 21:59:28.072 26920 26920 E AndroidRuntime: android.runtime.JavaProxyThrowable: Microsoft.Data.Sqlite.SqliteException (0x80004005): SQLite Error 14: ‘unable to open database file’.
10-18 21:59:28.072 26920 26920 E AndroidRuntime: at Microsoft.Data.Sqlite.SqliteException.ThrowExceptionForRC (System.Int32 rc, SQLitePCL.sqlite3 db) [0x00067] in :0
10-18 21:59:28.072 26920 26920 E AndroidRuntime: at Microsoft.Data.Sqlite.SqliteConnection.Open () [0x00109] in :0
10-18 21:59:28.072 26920 26920 E AndroidRuntime: at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenDbConnection (System.Boolean errorsExpected) [0x00061] in :0
10-18 21:59:28.072 26920 26920 E AndroidRuntime: at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.Open (System.Boolean errorsExpected) [0x0002a] in :0
10-18 21:59:28.072 26920 26920 E AndroidRuntime: at Microsoft.EntityFrameworkCore.Sqlite.Storage.Internal.SqliteRelationalConnection.Open (System.Boolean errorsExpected) [0x00000] in :0
10-18 21:59:28.072 26920 26920 E AndroidRuntime: at Microsoft.EntityFrameworkCore.Sqlite.Storage.Internal.SqliteDatabaseCreator.Create () [0x0000b] in :0
10-18 21:59:28.072 26920 26920 E AndroidRuntime: at Microsoft.EntityFrameworkCore.Storage.RelationalDatabaseCreator.EnsureCreated () [0x00010] in :0
10-18 21:59:28.072 26920 26920 E AndroidRuntime: at Microsoft.EntityFrameworkCore.Infrastructure.DatabaseFacade.EnsureCreated () [0x00006] in :0
10-18 21:59:28.072 26920 26920 E AndroidRuntime: at FmClient.Api.ServerConnections.Open () [0x00007] in :0
10-18 21:59:28.072 26920 26920 E AndroidRuntime: at FmClient.ViewModel.MainWindowViewModel.Load () [0x00042] in :0
10-18 21:59:28.072 26920 26920 E AndroidRuntime: at FmXamarin.MainPage.OnAppearing () [0x000b9] in :0
10-18 21:59:28.072 26920 26920 E AndroidRuntime: at System.Runtime.CompilerServices.AsyncMethodBuilderCore+<>c.b__7_0 (System.Object state) [0x00000] in :0
10-18 21:59:28.072 26920 26920 E AndroidRuntime: at Android.App.SyncContext+<>c__DisplayClass2_0.b__0 () [0x00000] in :0
10-18 21:59:28.072 26920 26920 E AndroidRuntime: at Java.Lang.Thread+RunnableImplementor.Run () [0x00008] in :0
10-18 21:59:28.072 26920 26920 E AndroidRuntime: at Java.Lang.IRunnableInvoker.n_Run (System.IntPtr jnienv, System.IntPtr native__this) [0x00009] in :0
10-18 21:59:28.072 26920 26920 E AndroidRuntime: at (wrapper dynamic-method) Android.Runtime.DynamicMethodNameCounter.53(intptr,intptr)
10-18 21:59:28.072 26920 26920 E AndroidRuntime: at mono.java.lang.RunnableImplementor.n_run(Native Method)
10-18 21:59:28.072 26920 26920 E AndroidRuntime: at mono.java.lang.RunnableImplementor.run(RunnableImplementor.java:30)
10-18 21:59:28.072 26920 26920 E AndroidRuntime: at android.os.Handler.handleCallback(Handler.java:873)
10-18 21:59:28.072 26920 26920 E AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:99)
10-18 21:59:28.072 26920 26920 E AndroidRuntime: at android.os.Looper.loop(Looper.java:214)
10-18 21:59:28.072 26920 26920 E AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:6986)
10-18 21:59:28.072 26920 26920 E AndroidRuntime: at java.lang.reflect.Method.invoke(Native Method)
10-18 21:59:28.072 26920 26920 E AndroidRuntime: at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
10-18 21:59:28.072 26920 26920 E AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1445)

The text was updated successfully, but these errors were encountered:

Источник

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement. We’ll occasionally send you account related emails.

Already on GitHub?
Sign in
to your account


Closed

herotheone opened this issue

Sep 22, 2018

· 18 comments

Comments

@herotheone

What did you do?

I wanted to connect my pre-loaded sqlite database and bundled it within the Xcode project navigator.

What did you expect to happen?

I wanted to connect that database. I already have successful connection with simulator but no luck with real iPhone.

What happened instead?

I get this error:

2018-09-22 19:01:42.098199+0800 myWay[1069:233261] [logging-persist] cannot open file at line 42249 of [95fbac39ba]
2018-09-22 19:01:42.098231+0800 myWay[1069:233261] [logging-persist] os_unix.c:42249: (0) open(/var/containers/Bundle/Application/B93852F8-F874-445F-911C-624CEDD765C3/myWay.app/db2.sqlite-wal) — Undefined error: 0
2018-09-22 19:01:42.098246+0800 myWay[1069:233261] [logging-persist] unable to open database file
SQLite error 14: unable to open database file

Demo Project

https://github.com/herotheone/myWay

@groue

Hello @herotheone

Error code 14 stands for SQLITE_CANTOPEN, «unable to open database file». I don’t know why SQLite is unable to open your database. But did you check, for example, that there exists a database file at the path you provide?

@herotheone

In the simulator everything works perfectly. I think i need to copy that sqlite file right ?
How can i copy that sqlite file to iPhone’s path folder ? Is there a way to do it with FileManager.copyItems(at: to:) ?

@groue

What path are you currently using? The one that works on the simulator, but fails on the device?

@herotheone

let dbPath = Bundle.main.path(forResource: "db2", ofType:"sqlite")
        
       do {
            
            let dbQueue = try DatabaseQueue(path: dbPath!)
            
            try dbQueue.inDatabase { db in
                
                //Select all data from the table named tablename residing in SQLite
               
                let rows = try Row.fetchCursor(db, "SELECT * FROM ZIMPORT")
                
                while let row = try rows.next() {
                    
                  let someString : String = row["gAnahtarKelime"]
                    let someString2 : String = row["gMana1"]
                    let someString3 : String = row["gMana2"]
                    let someString4 : String = row["gMana3"]
                    print("Anahtar Kelime : (someString)")
                    print("Mana 1 : (someString2)")
                    print("Mana 2 : (someString3)")
                    print("Mana 3 : (someString4)")
                   
                }
            }
        } catch {
            
            print(error.localizedDescription)
            
        }

@groue

This looks correct. Now make sure that all those sentences below are true. Do check them, don’t simply assume they are true:

  • you have a db2.sqlite resource in your project.
  • you made sure that this resource is bundled in your application, on the device.
  • you initialize a DatabaseQueue object only once in the lifetime of your application.
  • the format of the db2.sqlite file is compatible with the version of SQLite that ships with the iOS version on your device.

If you still have error SQLITE_CANTOPEN after those checks, then I really don’t know what is happening.

@groue

Also, since the log you provide in the initial comment contains db2.sqlite-wal, I conclude that your database is not a simple db2.sqlite file. It has been opened in the WAL mode at some point.

Do you also use DatabasePool? Don’t mix DatabaseQueue and DatabasePool. Choose one. And create one in the lifetime of your application.

Do you attempt at modifying the content of the database? You can not do that if the database is bundled as a resource, because resources can not be modified by the application. To make sure the database resource is not modified, open the database in the read-only mode:

var config = Configuration()
config.readonly = true

// Choose ONE of those, not both.
// And run this code ONCE in the life time of your app:
let dbQueue = try DatabaseQueue(path: ..., configuration: config)
let dbPool = try DatabasePool(path: ..., configuration: config)

@groue

And look at the FAQ, especially How do I open a database stored as a resource of my application?

@herotheone

Yes i edited the SQL file that is correct.
I will let you know with updates

@herotheone

var dbPath : String = ""
        var dbResourcePath : String = ""
        
        
        var config = Configuration()
        config.readonly = true
       
        let fileManager = FileManager.default
        do{
         dbPath = try fileManager
            .url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
            .appendingPathComponent("db2.sqlite")
            .path
        if !fileManager.fileExists(atPath: dbPath) {
            dbResourcePath = Bundle.main.path(forResource: "db2", ofType: "sqlite")!
            try fileManager.copyItem(atPath: dbResourcePath, toPath: dbPath)
        }
        }catch{
            print("An error has occured")
        }
        
        
       do {

        let dbQueue = try DatabaseQueue(path: dbPath, configuration: config)

            try dbQueue.inDatabase { db in

                //Select all data from the table named tablename residing in SQLite

                let rows = try Row.fetchCursor(db, "SELECT * FROM ZIMPORT")

                while let row = try rows.next() {

                  let someString : String = row["gAnahtarKelime"]
                    let someString2 : String = row["gMana1"]
                    let someString3 : String = row["gMana2"]
                    let someString4 : String = row["gMana3"]
                    print("Anahtar Kelime : (someString)")
                    print("Mana 1 : (someString2)")
                    print("Mana 2 : (someString3)")
                    print("Mana 3 : (someString4)")

                }
            }
        } catch {
        
            print(error.localizedDescription)

        }

I edited my code like this. Still getting same error

@herotheone

I changed this line
let dbQueue = try DatabaseQueue(path: dbPath, configuration: config) with this
let dbQueue = try DatabaseQueue(path: dbPath)
Now it is working !!

@groue

Now it is working !!

Great! I don’t quite know what happened, but what counts is that your app can run. Happy GRDB!

@mohamede1945

I faced a similar issue and the solution is to execute the following command on the database before using it as read-only database (or part of the app’s bundle):

PRAGMA journal_mode=DELETE

See https://www.sqlite.org/wal.html Read-Only Databases section.

@herotheone

@ahmedk92

For noobs like me. If your database is read-only, and it was somehow created with WAL mode. You can change that to ‘DELETE’ with your database editor (e.g. DB Browser for SQLite) under «Edit Pragmas» or similar. This the GUI equivalent to @mohamede1945 ‘s answer.

Screen Shot 2019-07-16 at 5 51 08 PM

@rteuteu55

I faced a similar issue and the solution is to execute the following command on the database before using it as read-only database (or part of the app’s bundle):

PRAGMA journal_mode=DELETE

See https://www.sqlite.org/wal.html Read-Only Databases section.

This helped me, thank you !!

@seong7

@rteuteu55

PRAGMA journal_mode=DELETE

Can you let me know where you wrote it?

@rteuteu55

@seong7

@rteuteu55

PRAGMA journal_mode=DELETE

Can you let me know where you wrote it?

I use SQLite DB Browser and I just typed the command in the execute SQL tab.
I then saved the DB and it worked. Any SQL file editor where you can run SQL command should work I assume.

@groue

Today, before I ran a project, I suddenly crashed as soon as I ran it. It felt very strange.

Caused by: android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (Sqlite code 14): Could not open database, (OS error - 13:Permission denied)

seems to lack permissions according to the log prompt, because the project is only using storage, then look at the permissions in the androidmanifest.xml and see

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

these two permissions are in ah, this is what is the matter, baidu is not added under the permission. Finally, it suddenly occurred to me that my phone was running on Android6.0. Then, to verify it, I found a 4.0 system and ran it directly. Once I found the problem, I would solve it. Many permissions have appeared since Android6.0, even though they are configured in androidmanifest.xml, and must be requested manually, or the permissions must be turned on in Settings – applications – permissions.
after 6.0 system with some permissions can be carried out such operation:

public static final int REQUEST_EXTERNAL_STORAGE = 1;
private static String[] PERMISSIONS_STORAGE = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
/**
* Verify access to the sd card
*
* @param activity
*/
public boolean verifyStoragePermissions(Activity activity) {
/*******below android 6.0*******/
if (Build.VERSION.SDK_INT < 23) {
return true;
}
int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.READ_EXTERNAL_STORAGE);
if (permission != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE);
return false;
} else {
return true;
}

}

Override in the Activity that invokes the requested permission. 
/**
 * :: Callbacks to request permissions
 *
 * @param requestCode
 * @param permissions
 * @param grantResults
 */
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_EXTERNAL_STORAGE) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
showToast("Authorization Success");
} else {
showToast("Authorization failed, please set open permissions.");
}
}
}

You can change the permission name to request another permission. Keep a small journal and hopefully help someone in need.

Read More:

Понравилась статья? Поделить с друзьями:
  • Sqlgrammarexception error performing isolated work
  • Sqlexceptionhelper ошибка отношение не существует
  • Sqldumper error log
  • Sqlcmd error microsoft odbc driver 17 for sql server tcp provider error code 0x2746
  • Sqlceexception occurred native error 25035