我有一个带回以下行的 sql 语句:

我想从 JDBC 结果集中获取这些值作为两个对象。一个用于客户编号为 1 的客户,另一个用于客户 2。我希望这两个对象具有另一个数组值,其中包含对象值的相关标题。
结构最终看起来像这样(在 JSON 中):
{客户编号:1,[“对象 1”,“对象 2”,“对象 3”]},{客户编号:2,[“对象 4”,“对象 5”]}
我怎样才能用 JDBC 做到这一点?
您可以使用 Map 最初以您想要的格式收集结果。
Map<Integer, Set<String>> customerTitles = new HashMap<Integer, Set<String>>();
while(resultSet.next()) {
Integer custId = resultSet.getInt(1);
Set<String> titles = customerTitles.containsKey(custId) ?
customerTitles.get(custId) : new HashSet<String>();
titles.add(resultSet.getString(2));
customerTitles.put(custId, titles);
}
以这种方式收集它后,您可以遍历 Map 并依次遍历其中的 Set 并将它们转换为 JSON
// Convert to Json array here using your JSON library
for(Integer custId : customerTitles.keySet()) {
for(String title : customerTitles.get(custId)) {
}
}
我能想到的两种方法。
通过查询获取CustomerNo第一个SELECT DISTINCT并将其保存在COLLECTION. 然后 for each (使用循环)CustomerNo执行COLLECTIONa并为 eachSELECT Title from table WHERE CustomerNo = <collectionValue>创建一个新的。JSON ObjectCustomerNo
用. RESULTSET_ SELECT CustomerNo, Title FROM tablename ORDER BY CustomerNo在RESULTSET将变量分配给CustomerNo您从中获取的获取代码(循环内)中RESULTSET并检查下一行。如果遇到新的CustomerNo则创建一个新的JSON Object.