Elo
Elo

Reputation: 306

Apex, SOQL, add results from database to the List, error

I would like to add results from database to the List. But there is a bug.

String str = '\'AOC\',\'BPD\',\'CRE\'';
List<String> lstString = str.split(',');
List<Shop_Product__c> productList = new List<Shop_Product__c>();
Integer i = 0;
for (String record: lstString) {
    System.debug('record[' + i + ']: ' + record);
    if ((record != null) && (productList != null)) {
      productList.add([SELECT Id, Brand__c 
                       FROM Shop_Product__c 
                       WHERE Brand__c = :record
                       LIMIT 10]);
      
      System.debug('productList[' + i + ']: ' + productList);
      System.debug('Here in for ----------------------------------------');
    }
    ++i;
}

Error is System.QueryException: List has no rows for assignment to SObject. Here is it the explain, but I don't understand what I should do.

Upvotes: 0

Views: 1088

Answers (1)

David Reed
David Reed

Reputation: 2759

The List method add() takes a single sObject. That's why you get the QueryException, just like in the examples you link to.

You can use the addAll() method to create a List<sObject> context, which avoids the exception if there are no responsive records.

Upvotes: 1

Related Questions