如何获取已经创建的.db并在Android Studio上使用它?

时间:2017-01-23 12:22:23

标签: android database android-studio

我的资源文件夹中有一个HOSPITALS.db文件。我想从DB访问数据。我已经有了一个用于访问表中数据的代码,我想访问.db文件本身,这样就不会产生错误而无法找到表。

protected void openDatabase() {
    db = openOrCreateDatabase("HOSPITALS", Context.MODE_PRIVATE, null);
}

1 个答案:

答案 0 :(得分:0)

使用以下

获取数据库路径
ContextWrapper cw =new ContextWrapper(getApplicationContext());
DB_PATH =cw.getFilesDir().getAbsolutePath()+ "/databases/"; //edited to databases

然后你就可以这样了

private void copyDataBase()
    {
        Log.i("Database",
                "New database is being copied to device!");
        byte[] buffer = new byte[1024];
        OutputStream myOutput = null;
        int length;
        // Open your local db as the input stream
        InputStream myInput = null;
        try
        {
            myInput =myContext.getAssets().open(DB_NAME);
            // transfer bytes from the inputfile to the
            // outputfile
            myOutput =new FileOutputStream(DB_PATH+ DB_NAME);
            while((length = myInput.read(buffer)) > 0)
            {
                myOutput.write(buffer, 0, length);
            }
            myOutput.close();
            myOutput.flush();
            myInput.close();
            Log.i("Database",
                    "New database has been copied to device!");


        }
        catch(IOException e)
        {
            e.printStackTrace();
        }
    }