简体   繁体   English

如何在房间数据库中实现sqlite查询?

[英]how to achieve sqlite query in room database?

This is SQLite query i want to use in room database here is the first to try insert data and if data is already exist then update the data by using id这是我想在房间数据库中使用的 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 supports @RawQuery annotation to construct queries at run-time. Room 支持 @RawQuery 注释以在运行时构造查询。 So you need:所以你需要:

@Dao
interface BooksDao{
    @RawQuery
    List<Book> books(SupportSQLiteQuery query);
}

And create your query in old school style:并以旧式风格创建您的查询:

String queryString = "here is your query";
List<Object> args = new ArrayList(); // here is your args for your query

And ther performe your query:然后执行您的查询:

SimpleSQLiteQuery query = new SimpleSQLiteQuery(queryString, args.toArray());
List<Book> result = booksDao.books(query);

You can achieve this with OnConflictStrategy.REPLACE您可以使用OnConflictStrategy.REPLACE实现此目的

@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insertBooks(vararg books: Book)

And you have to specify the id id as primary key并且您必须将 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM