2012-11-21 15 views
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 | 
+--------------- 

结果现在我想牛逼O访问每种颜色代码的数量,即单元格的值,所以我怎么有接近它在Java方面(JDBC).I've写了这个在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 ... 有关这方面的任何输入将不胜感激。

回答

2

您需要迭代结果集并提取每列值。通过所有行的

首先迭代,并设置其属性class

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建立,这是可以做到如下。

<% 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; 
} 
+0

感谢,但我想每个颜色的数量,如红色:3,蓝:1,绿色环保:2,它显示3为所有颜色代码。 –

+0

你是否改变了查询?你确定小组的条款还在吗?我没有看到任何会导致这种情况的代码,并不是说没有,但我没有看到它。 –

+0

我编辑了我的答案,但它仍然是正确的打印方式和一次。 –

1

实际上就像你对emp,idcolor - 你只需要在名称Count上查找列。也就是说,您的ResultSet将具有3的大小,并且每行将有两列:colorCount

我假设你已经知道如何在Java中谈论JDBC?

欢呼声,