第一个建议:阅读更多关于关系数据库和使用外键的表关系的信息,您将节省大量时间来连接这些表而不是name
列。
第二个建议:您可以使用单个查询来使用JOIN
句子获取所需的数据。
第三个建议:不要通过String
连接传递参数,而是使用 aPreparedStatement
来防止SQL 注入攻击。
第四个建议:如果您使用retrieveList<SomeClass>
而不是plain会更好ArrayList<String>
。这是因为您正在对接口进行编程,而不是对实现进行编程,并且您SomeClass
可以保存需要检索的属性。
将所有这些概念联系起来,您将拥有如下内容:
MySQL 语法:
CREATE TABLE TEAM_MEMBERS
(id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(100) NOT NULL);
CREATE TABLE PROJECT_TIME
(id INT PRIMARY KEY AUTO_INCREMENT,
hours INT NOT NULL,
date DATE NOT NULL,
teamMemberId INT NOT NULL,
FOREIGN KEY (teamMemberId) REFERENCES TEAM_MEMBERS(id));
使用 JOIN 的基本查询
SELECT tm.name, sum(pt.hours) AS hours -- retrieving both name and sum of hours at the same time
FROM
TEAM_MEMBERS tm --team members table
INNER JOIN PROJECT_TIME pt ON pt.teamMemberId = tm.id -- joining team members with project time table (not sure if this really makes sense, but is based on your code example)
WHERE
DATE = <some_date> -- used to show where the parameter will go
GROUP BY
tm.name -- used when using SUM or another AGGREGATE functions
在 Java 端使用这个基本查询:
//sample about the class
public class TeamMember {
private String name;
private int projectHours;
//constructor...
public TeamMember() {
}
//constructor sending parameters (because I'm lazy when having a class with few parameters)
public TeamMember(String name, int projectHours) {
this.name = name;
this.projectHours = projectHours;
}
//getter and setters...
}
List<TeamMember> teamMembers = new ArrayList<TeamMember>();
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
con = ... //initialize the connection
String query = "SELECT tm.name, sum(pt.hours) AS hours FROM TEAM_MEMBERS tm " +
"INNER JOIN PROJECT_TIME pt ON pt.teamMemberId = tm.id " +
"WHERE DATE = ? GROUP BY tm.name";
pstmt = con.prepareStatement(query);
pstmt.setString(1, date); //assuming you have your date in String format
//pstmt.setDate(1, date); //you could use this if your date variable is java.util.Date
rs = pstmt.execute();
while(rs.next()) {
teamMembers.add(new TeamMember(rs.getString("name"), rs.getInt("hours"));
}
} catch (Exception e) {
//handle the Exception
} finally {
//close the resources (this is a MUST DO)...
try {
if (rs != null) {
rs.close();
}
} catch (SQLException sqle) {}
try {
if (pstmt != null) {
pstmt.close();
}
} catch (SQLException sqle) {}
try {
if (con != null) {
con.close();
}
} catch (SQLException sqle) {}
}