加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

如何使用我自己的sqlite数据库?

发布时间:2020-12-12 19:05:58 所属栏目:百科 来源:网络整理
导读:我把我的数据库字段放在“assets”文件夹中.并使用此 blog中的代码将数据库复制到“/ data / data / my_packname / databases /”,(此复制代码我在运行此应用程序时在onCreate()方法中运行它)然后使用select * from ..获取数据但它给了我一个例外:没有这样
我把我的数据库字段放在“assets”文件夹中.并使用此 blog中的代码将数据库复制到“/ data / data / my_packname / databases /”,(此复制代码我在运行此应用程序时在onCreate()方法中运行它)然后使用select * from ..获取数据但它给了我一个例外:没有这样的表.

有人告诉我,如果我试图在SQLiteOpenHelper的onCreate()中复制文件,那就太晚了.因此复制文件代码无法复制完整的文件.

所以我需要先使用adb或ddms拉数据库吗?

那么,任何人都可以教我如何使用我自己的数据库?
你能告诉我这个设置吗?

我已经使用了该博客文章中的说明,并在正确的轨道上发现它们通过不必要地扩展SQLiteOpenHelper来严重地使问题复杂化.我做了以下更好的运气:

>创建一个实用程序类,通过将静态数据库从资产复制到正确的目录中来创建静态数据库,但不会因为SQLiteOpenHelper格式而陷入困境.
>使用相同的实用程序类通过使用SQLiteDatabase.openDatabase()打开数据库

编辑:这是我创建的这个实用程序类的一个版本;它不是很完整,但你会得到漂移.

public class DbUtils {
    private static final String DB_PATH = "/data/data/com.mypackage.myapp/databases/";
    private static final String DB_NAME = "my.db";

    public static void createDatabaseIfNotExists(Context context) throws IOException {
        boolean createDb = false;

        File dbDir = new File(DB_PATH);
        File dbFile = new File(DB_PATH + DB_NAME);
        if (!dbDir.exists()) {
            dbDir.mkdir();
            createDb = true;
        }
        else if (!dbFile.exists()) {
            createDb = true;
        }
        else {
            // Check that we have the latest version of the db
            boolean doUpgrade = false;

            // Insert your own logic here on whether to upgrade the db; I personally
            // just store the db version # in a text file,but you can do whatever
            // you want.  I've tried MD5 hashing the db before,but that takes a while.

            // If we are doing an upgrade,basically we just delete the db then
            // flip the switch to create a new one
            if (doUpgrade) {
                dbFile.delete();
                createDb = true;
            }
        }

        if (createDb) {
            // Open your local db as the input stream
            InputStream myInput = context.getAssets().open(DB_NAME);

            // Open the empty db as the output stream
            OutputStream myOutput = new FileOutputStream(dbFile);

            // transfer bytes from the inputfile to the outputfile
            byte[] buffer = new byte[1024];
            int length;
            while ((length = myInput.read(buffer)) > 0) {
                myOutput.write(buffer,length);
            }

            // Close the streams
            myOutput.flush();
            myOutput.close();
            myInput.close();
        }
    }

    public static SQLiteDatabase getStaticDb() {
        return SQLiteDatabase.openDatabase(DB_PATH + DB_NAME,null,SQLiteDatabase.OPEN_READONLY);
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读