如何从servlet中的数据库中检索数据

how to retrieve data from database in servlet

我是 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>"); 

我尝试了很多不同的方法,但没有运气....你能告诉我哪里错了吗

我看到了一些问题。 首先,我认为您的 select 方法应该 return 一个用户列表。 所以你可以像下面那样实现它

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 中你可以调用这个方法来 return 这个列表 并展示它。

 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>"); 

就是这样。 逻辑是我不确定它是否会起作用,可能会忘记一些细节,但这是可行的方法。 希望对您有所帮助。