我有带回以下行的SQL语句:如何从JDBC结果得到行值的阵列设置
我想获得一个JDBC这些值结果集的两个对象。一个用于customerNo 1和另一个用于customer 2的客户。我希望这两个对象具有另一个具有对象值的相关标题的数组值。
结构最终将看起来像这样(在JSON):
{customerNo:1,[ “对象1”, “对象2”, “对象3”]},{customerNo:2,[”对象4“,”对象5“]}
我该如何用JDBC来实现?
我有带回以下行的SQL语句:如何从JDBC结果得到行值的阵列设置
我想获得一个JDBC这些值结果集的两个对象。一个用于customerNo 1和另一个用于customer 2的客户。我希望这两个对象具有另一个具有对象值的相关标题的数组值。
结构最终将看起来像这样(在JSON):
{customerNo:1,[ “对象1”, “对象2”, “对象3”]},{customerNo:2,[”对象4“,”对象5“]}
我该如何用JDBC来实现?
您可以使用地图以您想要的格式开始收集结果。
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);
}
一旦你拥有了它这种方式收集的,你可以在地图和在圈内的集遍历并将其转换为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
。 然后对于中的每个(使用循环)CustomerNo
执行SELECT Title from table WHERE CustomerNo = <collectionValue>
并为每个CustomerNo
创建新的JSON Object
。
取RESULTSET
与SELECT CustomerNo, Title FROM tablename ORDER BY CustomerNo
。 在RESULTSET
的获取代码(在循环内部)中,将一个变量分配给您从RESULTSET
获得的CustomerNo
并检查下一行。如果您遇到新的CustomerNo
,则创建一个新的JSON Object
。
这是我会怎么做了。 'Set's不能包含重复,这可能是一个问题。如果遇到麻烦,请使用列表。 –