我是java servlet中的初学者...我正在进行curd操作... ...数据不显示请告诉我哪里错了....
DAO.java
public void select(){
try{
Class.forName(jdbcDriver);
Connection conn = DriverManager .getConnection(connectionString,username,password);
PreparedStatement create = conn.prepareStatement("select * from student.users");
ResultSet rs;
rs = create.executeQuery();
while(rs.next()){
int id =rs.getInt("id");
String name = rs.getString("fname");
}
}
catch(Exception e){
e.printStackTrace();
}
}
servlet.java
DAO user = new DAO(); /// i create object of DAO
user.select(); //calling select method
out.write("<td>");
out.write("<p>"+user.id+"</p>"); ///tried many from different way
out.write("</td>");
out.write("<td>");
out.write("<p>"+user.name+"</p>"); ///
out.write("</td>");
我从不同的方式尝试了许多但没有运气....你能告诉我我错在哪里
答案 0 :(得分:0)
我看到一些问题。 首先,我认为你的select方法应该返回一个用户列表。 所以你可以按照下面的方式实现它
public List<User> select(){
List<User> result = new ArrayList<User>();
try{
Class.forName(jdbcDriver);
Connection conn = DriverManager .getConnection(connectionString,username,password);
PreparedStatement create = conn.prepareStatement("select * from student.users");
ResultSet rs;
rs = create.executeQuery();
while(rs.next()){
int id =rs.getInt("id");
String name = rs.getString("fname");
User user = new User(); // Creating a user object to fill with user data (I imagine that you have a user class in your model)
user.setId(id);
user.setName(name);
//Add the retrived user to the list
result.add(user);
}
//Returning the list of users.
return result;
}catch(Exception e){
e.printStackTrace();
return null;
}
}
因此,在您的servlet中,您可以调用此方法来返回此列表 并展示它。
DAO daoUser = new DAO(); /// i create object of DAO
List<User> users = daoUser.select(); //calling select to get list of users
out.write("<table>");
for(User user : users){ //Running through the list to show all users retrived
out.write("<td>");
out.write("<p>"+user.id+"</p>");
out.write("</td>");
out.write("<td>");
out.write("<p>"+user.name+"</p>"); ///
out.write("</td>");
}
out.write("</table>");
就是这样。 我不确定它是否会起作用的逻辑可能会忘记一些细节,但这是可行的方法。 希望有所帮助。