本文介绍了如何从Android Room中的多个数据库中选择(如何附加数据库)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如您所知,我们可以使用如下附加命令从多个数据库中进行选择:
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.
通过使用Android Room,我该怎么做?有任何附件或类似的命令可以做到这一点吗?
By using Android Room, How can I do this? Is there any attachment or similar command to do this?
推荐答案
可以使用此代码附加另一个数据库
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);
}
}
在Dao界面中,使用@SkipQueryVerification
这样的跳过查询验证.
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);
...
}
使用:
LoanDatabase db = LoanDatabase.getInstance(this,"LoanDatabase1")
Book book= db.bookDao().getBookAndLoan(1)
这篇关于如何从Android Room中的多个数据库中选择(如何附加数据库)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!