将Resultset插入Arraylist并显示它们

Guo*_*hao 0 java sql jdbc

我很难将多个结果集存储到ArrayList中.我还需要在JTextArea中显示它们.但问题是,我不能让它显示任何东西.

public static ArrayList<Wall> getWallPosts(int postId){

    ArrayList<Wall> postList = new ArrayList<Wall>();
    ResultSet rs = null;
    DBController db = new DBController();

    db.setUp("myDatabase");
    String dbQuery = "SELECT Id FROM Wall WHERE ID ="+postId; 

    rs = db.readRequest(dbQuery);

    try{
       while (rs.next()){
            int wallId = rs.getInt("Id");
            String wallPoster = rs.getString("Poster");
            String wallPost = rs.getString("Post");
            String wallDate = rs.getString("Tdate");
            Wall w1 = new Wall(wallPoster, wallPost , wallDate);
            postList.add(w1);   
       }
    }
    catch (Exception e) {
       e.printStackTrace();
    }


    db.terminate();
    return postList;

}
    //The method for displaying the result sets
        public void retrieveCategoryQuestionList() {
    //get the list and store in array
    ArrayList<Wall> aList = Wall.getWallPosts(id);
    for(id = 1; id<aList.size();id++)
        jTextAreaWall.append(w2.getPost());
}
Run Code Online (Sandbox Code Playgroud)

数据库中的字段是Id,Poster,Post,Tdate

Bal*_*usC 5

这是你的SQL查询:

"SELECT Id FROM Wall WHERE ID ="+postId
Run Code Online (Sandbox Code Playgroud)

你只有选择Id从表中,而你希望Id,Poster,PostTdate在场按您的ResultSet#getString()来电.

String wallPoster = rs.getString("Poster");
String wallPost = rs.getString("Post");
String wallDate = rs.getString("Tdate");
Wall w1 = new Wall(wallPoster, wallPost , wallDate);
Run Code Online (Sandbox Code Playgroud)

您还需要在SQL查询中指定这些列:

"SELECT Id, Poster, Post, Tdate FROM Wall WHERE Id="+ postId
Run Code Online (Sandbox Code Playgroud)

也可以看看:


与具体问题无关,我建议让自己熟悉,PreparedStatement因为这是防止SQL注入攻击的原因.


更新:根据您自己的问题的评论,如果您的意图是显示所有行,那么您应该不添加限制性WHERE条款,即使没有,Id=0只会搜索匹配的记录Id=0.只是省略了WHERE.

"SELECT Id, Poster, Post, Tdate FROM Wall"
Run Code Online (Sandbox Code Playgroud)

我再次建议您完成基本的SQL教程.这个问题实质上与Java/JDBC没什么关系.除了一些严肃的设计问题,它应该可行.