Apex,SOQL,将数据库中的结果添加到列表中,错误

问题描述

我想将数据库中的结果添加到列表中。但是有一个错误

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

错误System.QueryException:列表没有可分配给 SObject 的行Here 是它的解释,但我不明白我应该做什么。

解决方法

List 方法 add() 接受单个 sObject。这就是您获得 QueryException 的原因,就像您链接到的示例一样。

您可以使用 addAll() 方法创建一个 List<sObject> 上下文,从而避免在没有响应记录时出现异常。