0

在我的应用程序中,我将颜色存储在我的表中emp,如下所示:

+---------+------------------+
| emp     |  id      | color |
+---------+------------------+
| hary    | 123      |  red  |
+---------+------------------+
| lary    | 125      | green |
+---------+------------------+
| gary    | 038      |  red  |
+---------+------------------+
| Kris    | 912      | blue  |
+---------+------------------+
| hary    | 123      |  red  |
+---------+------------------+
| Ronn    | 334      | green |
+---------+------------------+

现在为了计算颜色代码出现的次数,我写了这个:

select color,count(*) Count
from emp where (color like '%bl%' or color like '%ree%')
group by color

所以我得到这样的结果

+---------------
| color |Count |
+---------------
|   red |   3  | 
+---------------
|  blue |   1  | 
+---------------
| green |   2  | 
+---------------

现在我想访问每个颜色代码的计数,即单元格值,那么我必须如何根据 java(jdbc) 来处理它。我已经在 jsp 页面中写了这个:

<html
<body>
<div>
<table>
<% while(rs.next()){ %>

    <tr>
      <th>HDYK Stat</th><th>NUMBER</th>
     </tr>

    <tr style="color: #0DA068">
      <td><%=rs.getString("color") %></td><td><%= rs.getInt("Count")%></td>
    </tr>

    <tr style="color: #194E9C">
      <td><%=rs.getString("color") %></td><td><%= rs.getInt("Count")%></td>
    </tr>
   <tr style="color: #ED9C13">
   <td><%=rs.getString("color") %></td><td><%= rs.getInt("Count")%></td>
   </tr>

<%      
} 
%>
</table>
</div>
</body>
</html>

但它重复了 3 次:如红色:3,蓝色:3,绿色:1,红色:1,蓝色:1,绿色:1,红色:2... 任何有关这方面的输入将不胜感激。

4

2 回答 2

2

您需要遍历结果集并提取每个列的值。

public static void viewTable(Connection con)
    throws SQLException {

    Statement stmt = null;
    String query =
        "select color,count(*) Count from emp where (color like '%bl%' or color like'%ree%') group by color";

    try {
        stmt = con.createStatement();
        ResultSet rs = stmt.executeQuery(query);
        while (rs.next()) {
            String color = rs.getString("color");
            int count = rs.getInt("Count");
            System.out.println("Color: " + color + " Count: " + count);
        }
    } catch (SQLException e ) {
        //Something
    } finally {
        if (stmt != null) { stmt.close(); }
    }
}

虽然,我不建议通过 JSP 访问您的结果集,但可以按如下方式完成:

首先遍历所有行并设置它们的class属性。

<% while(rs.next()){ %>

    <tr>
      <th>HDYK Stat</th><th>NUMBER</th>
     </tr>

    <tr class="<%=rs.getString("color") %>">
      <td><%=rs.getString("color") %></td><td><%= rs.getInt("Count")%></td>
    </tr>
<%      
} 
%>

为 CSS 中的每种颜色定义样式

.red{
  color: #0DA068;
}

.blue{
  color:#194E9C;
}

.green{
  color: #ED9C13;
} 
于 2012-11-21T11:36:39.683 回答
1

实际上就像您想要的那样empid或者color-您只需按名称查找列Count。也就是说,您ResultSet的大小为 3,每行将有两列:colorCount.

我假设您已经知道如何在 Java 中使用 JDBC?

干杯,

于 2012-11-21T11:33:43.457 回答