在Android上创建SQLite数据库的最佳实践

ewj*_*mes 2 android

我已经阅读了很多关于将数据库文件从资产或原始文件夹复制到文件夹的帖子/data/data/APP/databases,但这会在设备上留下两个DB副本占用宝贵的空间.我正在考虑构建一个占用空间略小的解决方案,并通过将数据库SQL创建文本文件存储在原始文件夹中并使用on_create / on_updateDBhelper类中的标准流程来实现更灵活的模式管理.但是我有点困惑,因为复制数据库的示例绕过了on_create and on_update方法.

如果您不是从代码中的字符串构建db,这是推荐的方法吗?

我的解决方案是通过将脚本全部放在一个文件中来模拟代码方法中运行的脚本.我正在考虑以这种方式构建数据库的原因是,当应用程序完成时,我的数据库将有近100个表,所以我需要架构是可管理的.

欢迎任何指导,因为我仍在学习Android的最佳实践和模式.

这是我的代码示例:

public class DatabaseHelper extends SQLiteOpenHelper {
    private final String DATABASE_NAME = "mydb";
    private final int DATABASE_VERSION = 1;
    private final Context myCtx;
    private String DATABASE_CREATE_SCRIPT = null;

    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        DATABASE_CREATE_SCRIPT = getLoadFile();

        // Create all tables and populate the lookup tables
        db.execSQL(DATABASE_CREATE_SCRIPT);
        db.execSQL(VIEW_CREATE_V_PERSON);
    }

    private String getLoadFile(){
        InputStream inputStream = myCtx.getResources().openRawResource(resIdofmyfile);

        InputStreamReader inputreader = new InputStreamReader(inputStream);
        BufferedReader buffreader = new BufferedReader(inputreader);
        String line;
        StringBuilder text = new StringBuilder();

        try {
        while (( line = buffreader.readLine()) != null) {
           text.append(line);
           text.append('\n');
         }
        } catch (IOException e) {
           // We have an error to look up
           return null;
        }
        return text.toString();
    } 

    /**
     *  onUpgrade will check the version of the database and update the database 
     *  if a newer version is available.
     */
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // Will set conditional upgrade checks
        //Log.w(TAG, "Upgrading database from version " + oldVersion + " to " + newVersion + ", which may destroy all old data");
        db.execSQL("DROP TABLE IF EXISTS CONTEXT_LOAD");
            db.execSQL("DROP TABLE IF EXISTS ISSUES");
            db.execSQL("DROP TABLE IF EXISTS GOALS");
            db.execSQL("DROP TABLE IF EXISTS PERSON");

            db.execSQL("DROP VIEW IF EXISTS V_PERSON");
        onCreate(db);
    }


}
Run Code Online (Sandbox Code Playgroud)

C.d*_*.d. 6

我想这看起来很不错.即使您完全使用代码创建数据库,它也不是很糟糕.查看谷歌应用程序的IO计划,它有一个相当大的数据库创建部分.它可能会引导你.

是项目主页,是数据库部分

我一直使用这个应用程序作为参考,它就像一件艺术品=)


编辑: Google更新了应用,因此旧数据库链接无效.