Sas planet ошибка sqlite cantopen

Обновлено: 07.07.2024

После очистки хранилища и кеша приложения начала появляться неизвестная ошибка (код 14 SQLITE_CANTOPEN): не удалось открыть базу данных. До очистки хранилища все работало как на эмуляторе, так и на устройстве.

Я пытался удалить приложение из эмулятора, стер эмулятор и очистил проект, но все равно вылетал при открытии MainActivity. Ради решения проблем я поставил разрешения на запись в AndroidManifest, но все еще та же ошибка.

Вместо того чтобы делать

Что беспокоит меня, если я пытаюсь открыть базу данных, используя путь, который не включает имя базы данных - почему он работал до очистки хранилища и кэша приложения?

BazaPodatakaHelper.java

Журнал ошибок:

Поскольку ни один из вопросов по переполнению стека не помог мне, я собираюсь опубликовать, как я решил эту проблему. Раньше я пытался удалить базу данных из каталога проекта и /data/data/package, но это не помогло. Что решило мою проблему, так это удаление всей папки, где хранилась база данных, и повторное построение моего проекта. Теперь работает как последняя версия API Emulator, так и мое устройство.

Ваш код выше не включает ресурсы в путь, поэтому ваша проблема, вероятно, основана на этом.

Как правило, и в частности, если используется context.getDatabasePath(your_database) , попытка будет открыть

Дополнительно в ваших комментариях вы упоминаете: -

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

Таким образом, может случиться так, что вы пытаетесь открыть базу данных из того, что вы считаете папкой ресурсов, но вы не можете использовать папку включенных/импортированных ресурсов напрямую, так как активы управляются AssetsManager.

Возможно, вы могли бы использовать Device Explorer, чтобы создать папку ресурсов в /data/data/com.benjaminkljn.econdictionary, а затем скопировать базу данных в эту папку, и тогда открытие может сработать.

Если вы сделали это ранее, то после удаления/удаления приложения, если база данных не была скопирована вручную в папку ресурсов (и, следовательно, была создана папка активов), возникнет проблема, с которой вы столкнулись.

  • Когда приложение установлено, будет создана папка /data/data/com.benjaminkljn.econdictionary, но не базы данных подпапок, а не подпапка с именем assets, Очистка хранилища приложения фактически вернется к этой точке.

Однако ручное копирование базы данных будет работать только для конкретного приложения. Это не будет работать, если вы опубликовали приложение, так как у вас не будет доступа к копированию файла вручную.

Чтобы использовать уже существующую базу данных в приложении, рекомендуется: -

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:

Jackie1Wang commented Nov 9, 2018

meet the same issue, any one can help?

stiofand commented Jan 10, 2019

had this for months, any solution?

shafdog commented Jan 14, 2019

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

JonYergin commented Jul 31, 2019

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

rommzestz commented Oct 15, 2019

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

sousadgaspar commented Mar 28, 2020

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:

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

在项目里,仅打开一个数据库。还未进行读写等函数的调用。
--- translate ---
In the project, only one database is opened. No calls for functions such as read and write have yet been made.

`abstract class SQLiteOpenHelper @Protected
final String name;
@Protected
final int version;

SQLiteOpenHelper(
this.name,
this.version,
);

@Protected
Future getWritableDatabase() return getDatabase(
readOnly: false,
);
>

@Protected
Future getReadableDatabase() return getDatabase(
readOnly: true,
);
>

@Protected
Future onConfigure(Database db);

@Protected
Future onCreate(Database db, int version);

@Protected
Future onUpgrade(Database db, int oldVersion, int newVersion);

@Protected
Future onDowngrade(Database db, int oldVersion, int newVersion);

@Protected
Future onOpen(Database db);

@Protected
String selectionPlaceholder(List selectionArgs) StringBuffer buffer = new StringBuffer();
for (int i = 0; i < selectionArgs.length; i++) buffer.write(i != 0 ? ',' : '');
buffer.write('?');
>
return buffer.toString();
>
>`

`abstract class SimpleSQLiteOpenHelper extends SQLiteOpenHelper SimpleSQLiteOpenHelper(String name, int version) : super(name, version);

@OverRide
Future onConfigure(Database db) async <>

@OverRide
Future onOpen(Database db) async <>

@OverRide
Future onDowngrade(Database db, int oldVersion, int newVersion) async <>
>`

`class MessageTable static const String TABLE_NAME = 'message';

static const List COLUMNS = [
MessageData.KEY_SENDER,
MessageData.KEY_TYPE,
MessageData.KEY_URL,
MessageData.KEY_UNREAD,
MessageData.KEY_MSG,
MessageData.KEY_DATE,
];

static const int COLUMN_SENDER = 0;
static const int COLUMN_TYPE = 1;
static const int COLUMN_URL = 2;
static const int COLUMN_UNREAD = 3;
static const int COLUMN_MSG = 4;
static const int COLUMN_DATE = 5;

static String initTableScript() StringBuffer buffer = new StringBuffer();
buffer.write('create table if not exists ');
buffer.write(TABLE_NAME);
buffer.write(' ');
buffer.write('(');
buffer.write('$ text primary key,');
buffer.write('$ integer,');
buffer.write('$ text,');
buffer.write('$ integer,');
buffer.write('$ text,');
buffer.write('$ integer');
buffer.write(')');
return buffer.toString();
>
>

class ProfileTable static const String TABLE_NAME = 'profile';

static const List COLUMNS = [
ProfileData.KEY_SENDER,
ProfileData.KEY_URL,
ProfileData.KEY_NAME,
ProfileData.KEY_AVATAR,
];

static const int COLUMN_SENDER = 0;
static const int COLUMN_URL = 1;
static const int COLUMN_NAME = 2;
static const int COLUMN_AVATAR = 3;

static String initTableScript() StringBuffer buffer = new StringBuffer();
buffer.write('create table if not exists ');
buffer.write(TABLE_NAME);
buffer.write(' ');
buffer.write('(');
buffer.write('$ text primary key,');
buffer.write('$ text,');
buffer.write('$ text,');
buffer.write('$ text');
buffer.write(')');
return buffer.toString();
>
>

class IMDBHelper extends SimpleSQLiteOpenHelper static const int VERSION_1 = 1;

After clearing application storage & cache, started getting unknown error (code 14 SQLITE_CANTOPEN): Could not open database. Before clearing storage, everything was working properly, both Emulator and Device.

I tried deleting application from Emulator, wiped Emulator and cleaned project, but still crashing when opening MainActivity. For the sake of problem solving, I've put writing permissions in AndroidManifest but still the same error.

Instead of doing

What bothers me is if I'm trying to open database using a path that does not include the database name - why was it working before clearing application storage & cache?

BazaPodatakaHelper.java

Error Log:


37k 13 13 gold badges 41 41 silver badges 57 57 bronze badges 429 1 1 gold badge 6 6 silver badges 10 10 bronze badges well that was just a recommendation from my side as u would not have to take storage writing permission at all. and still be able to store data. and another recommendation that i would give u is use android Room lib @HarKal It was working without writing permissions. What would be better way for storing database?

1 Answer 1

The message is saying

Your code above does not include assets in the path, so your issue is probably based around that.

Typically, and specifically, if using context.getDatabasePath(your_database) , the attempt would be to open

Additionally in your comments you mention :-

Typically, importing the database, at least for an App, would be copying the database to be imported (included with the app) to the assets folder.

As such it could be that you are trying to open the database from what you think is the assets folder, but you cannot use the included/imported assets folder directly as the assets are managed by AssetsManager.

You could probably use Device Explorer to create the assets folder in /data/data/com.benjaminkljn.econdictionary and then copy the database into that folder and then the open may then work.

If you did that previously then, after deleting/uninstalling the App would, if the database hasn't been manually copied into the assets folder (and thus the assets folder has be created), result in the issue you have encountered.

  • When an App is installed the /data/data/com.benjaminkljn.econdictionary folder will be created but not the sub folders databases not the sub folder named assets, Clearing the App's storage effectively returns to this point.

However, manually copying the database, will only work for the specific App. It wouldn't work if you published the App, as you would not have access to copy the file manually.

To use a pre-existing database in an App then the recommended way is to :-

Читайте также: