如何从安卓空间的多个数据库中进行选择(如何附加数据库)

如您所知,我们可以使用附加命令从多个数据库中进行选择,如下所示:

String path = DBHelper.getDatabasePath(context);
String sql = "ATTACH DATABASE '" + path + "/" + dbname.toString()
                + ".db' AS \"" + dbname.toString() + "\";";
db.execSQL(sql);

然后通过使用Cursor,我们可以从中进行选择。

通过使用安卓房间,我该怎么做?是否有任何附件或类似命令来执行此操作?


答案 1

可以使用此代码附加另一个数据库

@Database(entities = {Book.class, User.class}, version = 1)
public abstract class LoanDatabase extends RoomDatabase {

    public abstract UserDao userDao();

    public abstract BookDao bookDao();

    private static LoanDatabase INSTANCE;

    public static LoanDatabase getInstance(Context context,final String attachDatabaseName) {
        if (INSTANCE == null) {{
            INSTANCE = Room.databaseBuilder(context,
                    LoanDatabase.class, "LoanDatabase").addCallback(new Callback() {
                @Override
                public void onOpen(@NonNull SupportSQLiteDatabase db) {
                    attach(attachDatabaseName,"/data/data/com.test.roomwithdagger/databases/");
                    super.onOpen(db);
                }
            })
                    .build();
        }}
        return INSTANCE;
    }

    private static void attach(final String databaseName, final String databasePath) {
        String sql = "ATTACH DATABASE '" + databasePath + databaseName
                + "' AS \"" + databaseName + "\";";
        INSTANCE. mDatabase.execSQL(sql);
    }
}

public void attachDatabase(String databaseName,String databasePath){

    String sql = "ATTACH DATABASE '" + databasePath + "/" + databaseName
            + ".db' AS \"" + databaseName + "\";";
    INSTANCE.mDatabase.execSQL(sql);
}
}

在 Dao 接口中,使用这样的跳过查询验证。@SkipQueryVerification

@Dao
public interface BookDao {

...

    @SkipQueryVerification
    @Query("SELECT * FROM main.Book b INNER JOIN LoanDatabase1.Loan l on b.Id=l.BookId where b.Id=:bookId")
    Book getBookAndLoan(int bookId);
...

}

用:

LoanDatabase db = LoanDatabase.getInstance(this,"LoanDatabase1")

Book book= db.bookDao().getBookAndLoan(1)

答案 2

使用 DatabaseBuilder 类构建会议室数据库时,您可以选择注册一个回调,该回调包含每次打开数据库时都会调用的方法:

 /**
         * Called when the database has been opened.
         *
         * @param db The database.
         */
        public void onOpen(@NonNull SupportSQLiteDatabase db) {
        }

一种选择是使用该参数注册此回调和其他数据库。然后在 dao 中,您可以拥有引用其他表的查询。ATTACHdb


推荐