How to add initial data to SQLite database?

后端 未结 6 1600
逝去的感伤
逝去的感伤 2021-02-14 07:04

I need to add initial values to SQLite database, once application is started first time. How should I do it?

6条回答
  •  有刺的猬
    2021-02-14 07:40

    In case you are using org.droidparts library OR-Mapper for accessing your database you can do it like this.

    In your implementation of

    public class CategoryEntityMgr extends EntityManager {
        public CategoryEntityMgr(Context ctx) {
            super(Category.class, ctx);
        }
    
        // NEW --> this one must be used in onCreateTables or you will receive a database locked exception
        private CategoryEntityMgr(Context ctx, SQLiteDatabase db) {
            super(Category.class, ctx, db);
        }
    }
    

    In your implementation of AbstractDbOpenHelper:

    protected void onCreateTables(SQLiteDatabase db) {
        // create your tables as usual
        createTables(db, Booking.class, Category.class);
    
        // Use a new instance of your entity manager
        //    but use the 2nd constructor to provide the db connection
        CategoryEntityMgr mgr = new CategoryEntityMgr(ctx, db);
    
        // add the new table row / entity you an to have
        Category c = new Category();
        c.name = "the value for this column";
        mgr.createOrUpdate(c);
    }
    

提交回复
热议问题