在androidStudio中,右键项目的src,选择assets folder,然后把外部数据库放入改目录下:

然后新建一个类,名为ImportDB类,输入如下代码(亲测可用!)
public class ImportDB {
private final int BUFFER_SIZE = 400000;
public static final String DB_NAME = "studb.db"; //保存的数据库文件名
public static final String PACKAGE_NAME = "bowles.com.stuadmin";//此处改为自己应用的包名。
public static final String DB_PATH = "/data/data/"
+ PACKAGE_NAME+"/databases"; //在手机里存放数据库的位置
private SQLiteDatabase database;
public Context context;
public ImportDB(Context context) {
this.context = context;
}
public void openDatabase() {
this.database = this.openDatabase(DB_PATH + "/" + DB_NAME);
}
public SQLiteDatabase openDatabase(String dbfile) {
try {
if (!(new File(dbfile).exists()))
{
//没有创建文件夹
File f=new File(DB_PATH);
if (!f.exists()){
f.mkdir();
}
//判断数据库文件是否存在,若不存在则执行导入,否则直接打开数据库
InputStream is = this.context.getResources().openRawResource(
R.raw.studb); //欲导入的数据库
FileOutputStream fos = new FileOutputStream(new File(dbfile));
byte[] buffer = new byte[BUFFER_SIZE];
int count = 0;
while ((count = is.read(buffer)) > 0) {
fos.write(buffer, 0, count);
}
fos.close();
is.close();
}
SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(dbfile,
null);
return db;
} catch (FileNotFoundException e) {
Log.e("Database", "File not found");
e.printStackTrace();
} catch (IOException e) {
Log.e("Database", "IO exception");
e.printStackTrace();
}
return null;
}
//do something else h
public void closeDatabase() {
this.database.close();
}
}
然后在activity这样调用:
public ImportDB importDB;
importDB = new ImportDB(this);
importDB.openDatabase();
这样就把外部数据库导入了app内部了。
如图所示:

然后在需要查询数据库的时候这样写
SQLiteDatabase db=SQLiteDatabase.openOrCreateDatabase(ImportDB.DB_PATH + "/" + ImportDB.DB_NAME, null);
接下来就可以调用
db.execel()方法,来查询数据库了
至此,数据库已经导入成功
本文详细介绍如何在Android项目中导入外部数据库到app内部。通过在assets文件夹放置数据库,并使用自定义ImportDB类进行数据库导入及操作,实现数据库的无缝集成。

1万+

被折叠的 条评论
为什么被折叠?



