【问题标题】:how to achieve sqlite query in room database?如何在房间数据库中实现sqlite查询?
【发布时间】:2020-04-05 17:49:49
【问题描述】:

这是我想在房间数据库中使用的 SQLite 查询 这是第一个尝试插入数据,如果数据已经存在,则使用 id 更新数据

INSERT INTO books(id, title, author, year_published)  VALUES(@id, @title, @author, @year_published)
 ON DUPLICATE KEY UPDATE title = @title,  author = @author;

【问题讨论】:

标签: android database sqlite android-room


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    您可以使用 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
    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-09-27
      • 1970-01-01
      • 2020-09-17
      相关资源
      最近更新 更多