首页 > 解决方案 > Java-Output all the columns and rows of a ResultSet

问题描述

ta.setText is a TextArea where I want to show all my data from the database, after a button click. But with rs.get("name") I just output one value and it is always the last. How can I print out the whole table from the database, so all the information which are stored there?

            try { String newquery = "SELECT * FROM kunden";
            java.sql.PreparedStatement ps = con.prepareStatement(newquery);
            rs = ps.executeQuery(newquery);


            while (rs.next()){              

            ta.setText(rs.getString("name"));
            ta.setText(rs.getString("nachname"));
            }


        }// try
        catch(Exception e1) {
        JOptionPane.showMessageDialog(null, "fail");


      }
      }//actionperformed

标签: javamysqldatabase

解决方案


您可以构建一个字符串,然后使用 setText() 设置该字符串

StringBuilder builder = new StringBuilder();
while (rs.next()) {
   builder.append(rs.getString(“name”));
   builder.append(“ “);
   builder.append(rs.getString(“nachname”));
   builder.append(“\n“);       
}
ta.setText(builder.toString());

或者您使用 TextArea 存在的 append 方法

while (rs.next()) {
   ta.append(rs.getString(“name”));
   ta.append(“ “);
   ta.append(rs.getString(“nachname”));
   ta.append(“\n“);
}

推荐阅读