如何从Android Room中的多个数据库中选择(如何附加数据库)

时间:2018-04-25 06:42:02

标签: java android sqlite android-room android-architecture-components

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

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

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

使用Android Room,我该怎么做?是否有任何附件或类似命令来执行此操作?

2 个答案:

答案 0 :(得分:4)

可以使用此代码附加其他数据库

@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)

答案 1 :(得分:1)

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

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

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