android 读取本地数据库db文件(Android sqlite)
在Android中,要读取本地的.db
文件并使用SQLite数据库,你可以按照以下步骤操作:
- 将
.db
文件放置在Android项目的assets
文件夹中。 - 使用
SQLiteOpenHelper
或SQLiteDatabase
打开和查询该数据库文件。
以下是一个简单的例子,演示如何读取位于assets
文件夹中的example.db
文件:
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class DatabaseHelper extends SQLiteOpenHelper {
private static String DB_PATH = "";
private static String DB_NAME = "example.db";
private final Context mContext;
private SQLiteDatabase mDataBase;
public DatabaseHelper(Context context) {
super(context, DB_NAME, null, 1); // 1 is the database version
this.mContext = context;
DB_PATH = context.getApplicationInfo().dataDir + "/databases/";
try {
createDataBase();
openDataBase();
} catch (IOException e) {
throw new Error("ErrorCopyingDataBase");
}
}
private void createDataBase() throws IOException {
boolean dbExist = checkDataBase();
if (dbExist) {
// do nothing - database already exist
} else {
// By calling this method and passing in the name of our db file,
// it will check to see if there is a database by that name in
// our assets folder. If not, it doesn't overwrite.
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
throw new Error("ErrorCopyingDataBase");
}
}
}
private boolean checkDataBase() {
File dbFile = new File(DB_PATH + DB_NAME);
return dbFile.exists();
}
private void copyDataBase() throws IOException {
InputStream mInput = mContext.getAssets().open(DB_NAME);
OutputStream mOu
评论已关闭