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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1951805/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 03:54:49  来源:igfitidea点击:

How to access an existing sqlite database in Android?

androidsqlite

提问by Muhammad Maqsoodur Rehman

So far we have developed apps in android that create database on runtime. We like to know how can we access a pre-built or existing database/sqlite file in our android app? Please provide detail

到目前为止,我们已经在 android 中开发了在运行时创建数据库的应用程序。我们想知道如何在我们的 android 应用程序中访问预先构建的或现有的数据库/sqlite 文件?请提供详细信息

回答by Trevor Johns

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 pathvariable, and it should work.

只需将数据库的路径指定为path变量,它就可以工作。

回答by gantzer89

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.
  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. For creating it just run the following query on your db:

    CREATE TABLE android_metadata (locale TEXT);

    And add the corresponding locale, for example en_US

  1. 在您创建的任何表中包含 _id 字段,并确保它是查询任何表时要返回的列的一部分。
  2. 您可能会遇到类似Failed to open the database的错误关闭它。. 这是因为我们正在从现有文件复制数据库,而不是在由 sqlite android API 创建的数据库之上创建表,并且表 android_metadata 可能不存在。要创建它,只需在您的数据库上运行以下查询:

    CREATE TABLE android_metadata (locale TEXT);

    并添加相应的语言环境,例如 en_US

回答by Arunendra

Use this for accessing database in application :

使用它来访问应用程序中的数据库:

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

回答by James

First copy your SDCARD and give it's path in the variable "DBNAME" in the following example. it will be something like "/sdcard/persons.db" if you are directly pulling it to sdcard.

在以下示例中,首先复制您的 SDCARD 并在变量“DBNAME”中提供它的路径。如果您直接将其拉到 sdcard,它将类似于“/sdcard/persons.db”。