我目前正在尝试做的事情做得不好。目的是从MySQL表中获取所有信息并将其放入数组中。一旦进入数组,我将使用java中的优先级队列并尝试使用它...但这不是我现在坚持的问题。
public static void array(String args []){ //创建优先级队列
try {
String url = "jdbc:mysql://localhost:3306/project";
Connection conn = DriverManager.getConnection(url,"root","nbuser");
PreparedStatement stmt = conn.prepareStatement("SELECT user_id,s_date,e_date,d_date,department,projectname,projectapplication FROM booking");
ResultSet rs;
rs=stmt.executeQuery();
List<User> userList = new ArrayList<User>();
while(rs.next()) {
User user = new User(); //issue here with non-static variable
user.userid(rs.getString("user_id"));
user.s_date(rs.getObject("s_date"));
user.e_date(rs.getObject("e_date"));
user.d_date(rs.getObject("d_date"));
user.department(rs.getObject("department"));
user.projectname(rs.getObject("projectname"));
user.projectapplication(rs.getObject("projectapplication"));
user.priority(rs.getObject("priority"));
userList.add(user);
}
conn.close();
} catch (Exception e) {
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
}
}
目的是让它遍历表中的所有不同部分并将它们填充到一个数组中,但我仍然坚持填充数组。
感谢任何帮助。
编辑:
public class User {
public String userid;
public String s_date;
public String e_date;
public String d_date;
public String department;
public String projectname;
public String projectapplication;
public int priority;
private void userid(String string) {
throw new UnsupportedOperationException("Not yet implemented");
}
private void s_date(Object object) {
throw new UnsupportedOperationException("Not yet implemented");
}
private void e_date(Object object) {
throw new UnsupportedOperationException("Not yet implemented");
}
private void d_date(Object object) {
throw new UnsupportedOperationException("Not yet implemented");
}
private void department(Object object) {
throw new UnsupportedOperationException("Not yet implemented");
}
private void projectname(Object object) {
throw new UnsupportedOperationException("Not yet implemented");
}
private void projectapplication(Object object) {
throw new UnsupportedOperationException("Not yet implemented");
}
private void priority(Object object) {
throw new UnsupportedOperationException("Not yet implemented");
}
}
与此相似?
答案 0 :(得分:1)
使用SQL表中的相应字段创建一个User
类,并将每个用户保留在列表中。
List<User> userList = new ArrayList<User>();
while(rs.next()) {
User user = new User();
user.setId(rs.getString("user_id"));
user.setStartDate(rs.getTimestamp("s_date");
....
userList.add(user);
}
return userList;
编辑:
class User {
private String id;
private Date startDate;
//other fields need to be declared as well as their setter methods
public void setStartDate(Date startDate) {
this.startDate = startDate;
}
public void setId(String id) {
this.id = id;
}
}
我还建议您查看JPA
和Hibernate
。