问题描述
在SQLiteOpenHelper
中,有一种onCreate(SQLiteDatabase ...)
方法,我曾经用一些初始数据填充数据库表.
In SQLiteOpenHelper
there is a onCreate(SQLiteDatabase ...)
method which i used to populate database tables with some initial data.
推荐答案
已更新
您可以通过3种方式执行此操作:重要,请查看此信息以获取迁移详细信息
You can do this in 3 ways: important check this for migration details
1-从导出的资产架构中填充数据库
1- Populate your database from exported asset schema
Room.databaseBuilder(appContext, AppDatabase.class, "Sample.db")
.createFromAsset("database/myapp.db")
.build();
2-从文件填充数据库
2- Populate your database from file
Room.databaseBuilder(appContext, AppDatabase.class, "Sample.db")
.createFromFile(new File("mypath"))
.build();
3-您可以在创建数据库后运行脚本,也可以在每次使用RoomDatabase.Callback
打开数据库时运行脚本,此类在最新版本的Room库中可用.
3- You can run scripts after database is created or run every time database is opened using RoomDatabase.Callback
, this class is available in the latest version of the Room library.
您需要实现RoomDatabase.Callback
的onCreate
和onOpen
方法并将其添加到RoomDatabase.Builder
中,如下所示.
You need to implement onCreate
and onOpen
method of RoomDatabase.Callback
and add it to RoomDatabase.Builder
as shown below.
yourDatabase = Room.databaseBuilder(context, YourDatabase.class, "your db")
.addCallback(rdc)
.build();
RoomDatabase.Callback rdc = new RoomDatabase.Callback() {
public void onCreate (SupportSQLiteDatabase db) {
// do something after database has been created
}
public void onOpen (SupportSQLiteDatabase db) {
// do something every time database is open
}
};
您可以在RoomDatabase.Callback方法中使用Room DAO本身来填充数据库.有关完整示例,请参见分页和聊天室"示例
You can use Room DAO itself in the RoomDatabase.Callback methods to fill the database. For complete examples see Pagination and Room example
RoomDatabase.Callback dbCallback = new RoomDatabase.Callback() {
public void onCreate(SupportSQLiteDatabase db) {
Executors.newSingleThreadScheduledExecutor().execute(new Runnable() {
@Override
public void run() {
getYourDB(ctx).yourDAO().insertData(yourDataList);
}
});
}
};
这篇关于如何在首次运行时填充Android Room数据库表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!