android导入外部数据库

本文详细介绍如何在Android项目中导入外部数据库到app内部。通过在assets文件夹放置数据库,并使用自定义ImportDB类进行数据库导入及操作,实现数据库的无缝集成。

在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()方法,来查询数据库了

至此,数据库已经导入成功

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值