【问题标题】:Using Room persistence library alongside with sqlite将 Room 持久性库与 sqlite 一起使用
【发布时间】:2018-01-25 10:02:29
【问题描述】:

我有一个使用 Sqlite 存储数据的项目。现在我想创建一些表,并想使用 Room 持久性库创建这些表。 我可以使用 room 和 Sqlite Api 访问相同的数据库吗?

这是我的 sqlite 代码

public class DatabaseHelper extends SQLiteOpenHelper {

// Table names
static final String TABLE_FOOD = "_food_table";
static final String TABLE_CUISINE = "_cuisine_table";
static final String TABLE_UNITS = "_units_table";
static final String TABLE_INGREDIENTS = "_ingredients_table";
static final String TABLE_CART = "_cart_table";
public static final String CLIENT_TABLE_CART = "_client_cart_table";
static final String TABLE_SUPPLIER = "_supplier_table";

private static final String DB_NAME = "duplate.db";
private static final int DB_VERSION = 3;

这是我的 Room 数据库创建代码

@Database(entities = arrayOf(IngredientType::class), version = 3)
    abstract class AppDatabase : RoomDatabase() {

       abstract fun ingredientTypeDao(): IngredientTypeDao

       companion object {
           private val DB_NAME = "duplate.db"
          @Volatile
          private var instance: AppDatabase? = null

        @Synchronized
        fun getInstance(context: Context): AppDatabase? {
            if (instance == null) {
                instance = create(context)
            }
           return instance
        }

        private fun create(context: Context): AppDatabase {
            return Room.databaseBuilder(
                    context,
                    AppDatabase::class.java,
                    DB_NAME).build()
        }
    }}

我知道我需要使用迁移。如果迁移可以方便地同时使用这两个 api。需要建议。 现在我想使用 sqlite 或 room 访问相同的数据库。会不会有什么问题?任何建议都会有所帮助 谢谢

【问题讨论】:

  • 只要使用相同的数据库名称,一切都会好起来的,除了日志中的这个: SQLiteLog: (5) statement aborts at 1: [PRAGMA journal_mode=TRUNCATE] database is locked

标签: java android android-sqlite android-room


【解决方案1】:

我可以使用 room 和 Sqlite Api 访问同一个数据库吗?

不,你不能。 RoomDatabase 将是一个完全独立的数据库,您必须慢慢地将表移动到新数据库。这是使用 Room API 的唯一方法。

如果您列出的表是您项目中唯一的表,那么它看起来在相当短的时间内是可行的。我建议您使用EntitiesDaos 从头开始​​创建新数据库。您最大的挑战是将所有 SQLite 查询转换为 Daos,这可能会花费最多的时间,但最终还是值得的。

我知道我需要使用迁移。如果迁移很方便,可以同时使用这两个 api。

迁移仅用于处理Room 数据库内的数据库升级。这与在 SQLite 中调用 onUpgrade 相同。

按照本指南逐步移至Roomhttps://medium.com/google-developers/incrementally-migrate-from-sqlite-to-room-66c2f655b377

【讨论】:

    猜你喜欢
    • 2018-11-11
    • 2019-04-25
    • 1970-01-01
    • 2019-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-27
    • 2016-03-31
    相关资源
    最近更新 更多