简体   繁体   English

如何在Android中访问现有的sqlite数据库?

[英]How to access an existing sqlite database in Android?

So far we have developed apps in android that create database on runtime. 到目前为止,我们已经在android中开发了在运行时创建数据库的应用 We like to know how can we access a pre-built or existing database/sqlite file in our android app? 我们想知道如何在我们的Android应用程序中访问预先构建的或现有的数据库/ sqlite文件? Please provide detail 请提供详细信息

Take a look at the documentation for android.database.sqlite.SQLiteDatabase . 看一下android.database.sqlite.SQLiteDatabase的文档。

In particular, there's an openDatabase() command that will access a database given a file path. 特别是,有一个openDatabase()命令可以在给定文件路径的情况下访问数据库。

SQLiteDatabase db = SQLiteDatabase.openDatabase(path, null, 0);

Just specify the path to your database as the path variable, and it should work. 只需将数据库的path指定为path变量,它就可以工作。

I have followed the same road and found two issues: 我走了同样的道路,发现了两个问题:

  1. Include the _id field on any table you create and make sure it is part of the columns to return when you query any table. 在您创建的任何表上包含_id字段,并确保它是查询任何表时要返回的列的一部分。
  2. You may run into an error like Failed to open the database. 您可能会遇到像打开数据库失败这样的错误 closing it. 关闭它。 . This is because we are copying the database from an existing file instead of creating tables on top of a db created by the sqlite android API and the table android_metadata may not exist. 这是因为我们从现有文件复制数据库,而不是在sqlite android API创建的数据库之上创建表,并且表android_metadata可能不存在。 For creating it just run the following query on your db: 要创建它,只需在db上运行以下查询:

    CREATE TABLE android_metadata (locale TEXT);

    And add the corresponding locale, for example en_US 并添加相应的区域设置,例如en_US

Use this for accessing database in application : 用它来访问应用程序中的数据库:

Context context = getApplicationContext();
context.getDatabasePath(DataBaseHelper.database_Name);

First copy your SDCARD and give it's path in the variable "DBNAME" in the following example. 首先复制SDCARD并在以下示例中的变量“DBNAME”中给出它的路径。 it will be something like "/sdcard/persons.db" if you are directly pulling it to sdcard. 如果你直接将它拉到SD卡,它将类似于“/sdcard/persons.db”。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM