在我的应用程序中,我将颜色存储在表 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... 任何有关这方面的意见将不胜感激。
最佳答案
您需要迭代结果集并提取每列值。
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;
}
关于java - 想要访问选择查询的单元格的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13492370/