使用Android中的Realm更新表中的多行

时间:2016-08-05 06:12:09

标签: android database realm

我正在使用 Realm 将我的值存储在本地数据库中。

我的要求是我需要根据某些条件更改一个字段CInternetSession session; CHttpConnection* pServer = NULL; CHttpFile* pFile = NULL; CString szHeaders( _T("Content-Type: application/x-www-form-urlencoded;Accept: text/xml, text/plain, text/html, text/htm\r\nHost: www.mydomain.com\r\n\r\n")); CString strObject; DWORD dwRet; CByteArray dataBuf; dataBuf.SetSize(1024); try { INTERNET_PORT nPort(80); pServer = session.GetHttpConnection(_T("www.mydomain.com"), nPort); pFile = pServer->OpenRequest(CHttpConnection::HTTP_VERB_GET, strObject); pFile->AddRequestHeaders(szHeaders); pFile->SendRequest(); pFile->QueryInfoStatusCode(dwRet); if (dwRet == HTTP_STATUS_OK) { UINT nRead = pFile->Read(dataBuf.GetData(), dataBuf.GetSize()); } delete pFile; delete pServer; } catch (CInternetException* pEx) { TCHAR sz[1024]; pEx->GetErrorMessage(sz, 1024); pEx->Delete(); }

我尝试过以下方法来完成此任务。它工作正常。

status=1

现在我的本地数据库中可能有1000个这样的行,并且使用for循环更新单行似乎不正确。

所以我的问题:有没有像 RealmResults<NotificationOrder> notificationOrders=realm .where(NotificationOrder.class) .equalTo(RealmConstants.TBL_NOTIFICATION_ORDER.property_id,ConstantMethod.getPreference(getActivity(),UserDefault.kPropertyId)) .equalTo(RealmConstants.TBL_NOTIFICATION_ORDER.status,0) .findAll(); for (NotificationOrder order:notificationOrders) { realm.beginTransaction(); order.setStatus(1); realm.commitTransaction(); } 更新查询在Realm中通过单一语句更新所有状态= 0的行而不是逐个更新单行?

感谢。

2 个答案:

答案 0 :(得分:4)

如果我知道的话,交易中的对象应该被管理,所以

realm.executeTransaction(new Realm.Transaction() {
    @Override
    public void execute(Realm realm) {
       RealmResults<NotificationOrder> notificationOrders = realm
            .where(NotificationOrder.class)
            .equalTo(RealmConstants.TBL_NOTIFICATION_ORDER.property_id,ConstantMethod.getPreference(getActivity(),UserDefault.kPropertyId))
            .equalTo(RealmConstants.TBL_NOTIFICATION_ORDER.status,0)
            .findAll();
        for(NotificationOrder order : notificationOrders) {
            order.setStatus(1);
        }
    }
});

应该足够了。

答案 1 :(得分:0)

您可以通过setValue这样的方法批量更新:

realm.where(NotificationOrder.class)
.equalTo(RealmConstants.TBL_NOTIFICATION_ORDER.property_id,ConstantMethod.getPreference(getActivity(),UserDefault.kPropertyId))
            .equalTo(RealmConstants.TBL_NOTIFICATION_ORDER.status,0)
            .findAll()
            .setValue(RealmConstants.REALM_FIELD_NAME,value); // 1st parameter is field name, 2nd is value