![](/img/trans.png)
[英]How to customize Room Database Query results that we can achieve in normal SQLite Open helper class
[英]how to achieve sqlite query in room database?
这是我想在房间数据库中使用的 SQLite 查询,这是第一个尝试插入数据的查询,如果数据已经存在,则使用 id 更新数据
INSERT INTO books(id, title, author, year_published) VALUES(@id, @title, @author, @year_published)
ON DUPLICATE KEY UPDATE title = @title, author = @author;
Room 支持 @RawQuery 注释以在运行时构造查询。 所以你需要:
@Dao
interface BooksDao{
@RawQuery
List<Book> books(SupportSQLiteQuery query);
}
并以旧式风格创建您的查询:
String queryString = "here is your query";
List<Object> args = new ArrayList(); // here is your args for your query
然后执行您的查询:
SimpleSQLiteQuery query = new SimpleSQLiteQuery(queryString, args.toArray());
List<Book> result = booksDao.books(query);
您可以使用OnConflictStrategy.REPLACE实现此目的
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insertBooks(vararg books: Book)
并且您必须将 id id指定为主键
@Entity(tableName = "book_table")
data class Book(
@PrimaryKey val id: String,
val title: String,
val author: String,
val year_published: Int
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.