0

How can I get multiple rows from database and display it all either in jTextArea or in a jLabel?

try{
 String url = "jdbc:mysql://localhost/sched";
 Connection conn= DriverManager.getConnection(url,"root", "");
 Statement stmt =conn.createStatement();
 String classif=comboClass.getSelectedItem().toString();
 String sqlSelect="select * from doctorsched where class = '"+classif+"'";
 ResultSet rs= stmt.executeQuery(sqlSelect);
  while(rs.next()){
    String docsName=rs.getString("docsName");
    String room=rs.getString("room");
    jTextArea1.setText(docsName+" (room "+room+") \n");
    }
}catch(Exception e){
}

When I use this code, jTextArea1 only displays data from the last line or row of the database. The rest from the beginning is not visible. And if I'll use jLabel I'm sure it would also work this way. These two (jLabel and jTextArea) are my only options for this.

If someone could help me, I'd appreciate it so much. Thank you.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • Most people would display the results in a `JTable` so the data is presented in rows and columns. See: https://stackoverflow.com/questions/55627828/how-to-get-a-defaulttablemodel-objects-data-into-a-subclass-of-defaulttablemode/55635012#55635012 for a generic example. Also, don't use an empty catch block. You will never know when you have an SQL exception. – camickr Nov 12 '20 at 16:04

1 Answers1

0

You need to create JLabels dynamically for each result, because you are saving all in the same Jlabel so every time you call .setText("") you are removing the previous text and puting the new one. Example:

You have your JFrame or JPanel or any container

JFrame frame = new JFrame("Frame");

Then in every result you should do this:

while(rs.next()){
    String docsName=rs.getString("docsName");
    String room=rs.getString("room");
    JLabel tempLabel = new JLabel();
    tempLabel.setText(docsName + " (room" + room + ")");
    frame.add(tempLabel);
}

Another option if you want to use only one JLabel is concatenate all the results in a String variable like this:

String finalText = "";
while(rs.next()){
    String docsName=rs.getString("docsName");
    String room=rs.getString("room");
    finalText += docsName + " (room" + room + ")\n";
    
}
jTextArea1.setText(finalText);

I hope it helps you, Kind regards.

Edit: If you create dynamically the JLabel remember to set size, bounds, layout, etc by code before do frame.add()!!