【问题标题】:Resultset output in rows to be converted to single col output separated by comma行中的结果集输出将转换为以逗号分隔的单列输出
【发布时间】:2019-06-30 06:27:14
【问题描述】:

我正在尝试编写此 java 过程,以在单个 col 中显示此代码的输出,用逗号分隔,而不是多行。 在 printOut 部分,我想将行中的所有输出合并为每个用户 1 col。我尝试使用 ArrayList arr = new ArrayList() 和 设置 results = new HashSet() 以便我可以获取以逗号分隔的数组中的所有行值,如预期输出所示。

         ResultSet group=(ResultSet)Groups.getFieldValue(USER_GROUP_RESULTSET);//Gets all the user groups for the user
        printOut("Groupscount:"+group.getRowCount()); //Counts the # of user groups user is assigned to for printing purpose only
        group.moveFirst();
        while(!group.isEof()) {  //For all the user groups,list the user name and another col with all user groups separated by comma instead of individual rows.
        String groupname1= group.getFieldValueString(USER_GROUP); // fetches the user group name in the string. Do i need to use array here?
        printOut(USER+";"+groupname1); // It displays the output row wise
        group.moveNext();

                }

实际输出:
用户 1;XYZ
用户1;ABC

预期输出: 用户1; XYZ,ABC

【问题讨论】:

  • 首先正确缩进代码,以便能够阅读您的代码并理解其结构。
  • 对不起!只更新了我坚持的代码。
  • 您的groupOut 可能会打印一个换行符。我只是在这里猜测,因为我不知道您从ResultSet 获得什么数据。如果您有多行具有相同的第一列并且您想要组合它们,您需要做的不仅仅是打印,您需要创建一个哈希映射,您使用第一列作为键,然后连接其他数据同时遍历group。然后遍历该映射并打印累积值。如果这不能让您走上正轨,请edit 您的问题并附上minimal reproducible example。您可能还想阅读How to Ask
  • 您理解正确。我不想放太多与问题无关的代码。我错过了我现在添加的 1 段代码 String groupname1= group.getFieldValueString(USER_GROUP);因此,每次迭代的第一个 col 保持不变,我需要列出该 1 col 值的所有组。能否请您发布一个如何使用哈希映射的示例?

标签: java resultset


【解决方案1】:

您需要将 printOut 移到 while 循环之外

StringBuilder sb=new StringBuilder();
while(!group.isEof()) {
String groupname1=group.getFieldValueString(USER_GROUP);
sb.append(";"+groupname1);
group.moveNext();
}

printOut(USER+sb.toString());

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-12-10
    • 2020-09-17
    • 1970-01-01
    • 1970-01-01
    • 2018-01-29
    • 1970-01-01
    • 2011-04-25
    相关资源
    最近更新 更多