Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
371 views
in Technique[技术] by (71.8m points)

java - How to select from multiple databases in Android Room(How to attach databases)

As you know we can select from multiple databases using attach command like this:

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

Then by using Cursor, we can do select from them.

By using Android Room, How can I do this? Is there any attachment or similar command to do this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Can use this code for attach another database

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

In Dao interface use @SkipQueryVerification for skip query verification like this.

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

}

Use :

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...