【问题标题】:Android Room - RawQuery not working to update/insert data in the DBAndroid Room - RawQuery 无法在数据库中更新/插入数据
【发布时间】:2019-12-30 10:21:06
【问题描述】:

我正在使用房间库版本 1.1.1 进行数据库操作。我成功在房间里创建了一个表,但无法在其中插入/更新数据。执行原始查询后光标给我 0 值,但我看不到数据库中的数据。

在执行代码室时甚至没有给我异常,但是当我执行简单的插入查询时,它工作正常。

查询只是说如果我们在 Notifications 表中有 chatDialogId,则更新消息计数,或者如果它不可用,则添加一个消息计数为 1 的新原始数据。

提前致谢

实体类

@Entity(tableName = "Notifications")
public class Notifications {

    @PrimaryKey(autoGenerate = true)
    @ColumnInfo(name = "id")
    private long id;

    @ColumnInfo(name = "chatDialogId")
    private String chatDialogId;


    @ColumnInfo(name = "messageCount")
    private int messageCount;

    public Notifications() {
    }

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getChatDialogId() {
        return chatDialogId;
    }

    public void setChatDialogId(String chatDialogId) {
        this.chatDialogId = chatDialogId;
    }


    public int getMessageCount() {
        return messageCount;
    }

    public void setMessageCount(int messageCount) {
        this.messageCount = messageCount;
    }

}

@Dao
public interface SMDatabaseDao {

    @RawQuery
    public long insertUpdateNotificationCount(SupportSQLiteQuery query);
}

在收到消息时从 FCMIntentService 调用以下方法。

public Long insertUpdateNotificationCount(final String id) {
    return runInTransaction(new Callable<Long>() {
        @Override
        public Long call() throws Exception {
            String customQuery = "UPDATE Notifications SET messageCount=messageCount+1 WHERE chatDialogId='" + id + "' AND EXISTS ( SELECT 1 FROM Notifications WHERE chatDialogId='" + id + "'); " +
                    "INSERT into Notifications(chatDialogId,messageCount) SELECT '" + id + "', 1 WHERE not EXISTS ( SELECT 1 FROM Notifications WHERE chatDialogId='" + id + "');";

            return smDatabaseDao().insertUpdateNotificationCount(new SimpleSQLiteQuery(customQuery));


        }
    });
}

【问题讨论】:

    标签: android android-sqlite android-room


    【解决方案1】:

    官方文档说:

    RawQuery 方法只能用于读取查询。对于写查询,使用 RoomDatabase.getOpenHelper().getWritableDatabase().

    这里是阅读完整文档的链接。 @RawQuery

    【讨论】:

      猜你喜欢
      • 2023-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-24
      • 2021-12-12
      • 1970-01-01
      相关资源
      最近更新 更多