如何从JDBC结果集中获取行值的数组 [英] How to get array of row values from JDBC result set

查看:226
本文介绍了如何从JDBC结果集中获取行值的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一条sql语句,该语句带回以下行:

I have a sql statement that brings back the following rows:

我想从JDBC结果集中获得这些值作为两个对象.一个用于客户编号为1的客户,另一个用于客户编号2.我希望这两个对象具有另一个带有相关标题的数组值和对象值.

I would like to obtain these values from a JDBC result set as two objects. One for the customer with customerNo 1 and the other for customer 2. I would like the two objects to have another array value with the related Titles with the object values.

结构最终看起来像这样(在JSON中):

The structure would ultimately look like this (in JSON):

{customerNo:1,["Object 1","Object 2","Object 3"]},{customerNo:2,["Object 4","Object 5"]}

{customerNo : 1, ["Object 1", "Object 2", "Object 3"]}, {customerNo : 2, ["Object 4", "Object 5"]}

如何使用JDBC完成此操作?

How can I accomplish this with JDBC?

推荐答案

您可以使用地图以所需的格式最初收集结果.

You can use a Map to initially collect the results in the format you want.

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

Once you have it collected this way, you can iterate over the Map and in turn the Sets within and convert them to JSON

// Convert to Json array here using your JSON library
for(Integer custId :  customerTitles.keySet()) {
    for(String title : customerTitles.get(custId)) {

    }
}

这篇关于如何从JDBC结果集中获取行值的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆