-2

I want to retrieve data in jtable from MySQL database everything is right but the data present at index 1 are not shown plz loo image 1 and 2.

jtable img 1:

https://i.stack.imgur.com/PpXeo.png

MySQL table img2:

https://i.stack.imgur.com/20t82.png

 public void view_librarian() throws SQLException {
        prepareStatement = connection.prepareStatement("select * from librarian");
        ResultSet rs = prepareStatement.executeQuery();
        DefaultTableModel tm = (DefaultTableModel) table.getModel();
        table.setFont(new Font("Serif", Font.PLAIN, 25));
        table.setRowHeight(35);
        table.getTableHeader().setFont(new Font("Arial", Font.BOLD, 25));
        tm.setRowCount(0);
        if (rs.next()) {
            while (rs.next()) {
                Object o[] = {rs.getString("username"), rs.getString("name"), rs.getString("mobile"), rs.getString("email"), rs.getString("address"), rs.getString("date_time")};
                tm.addRow(o);
            }
        } else {
            JOptionPane.showMessageDialog(this, "No data found");
        }
    }
camickr
  • 321,443
  • 19
  • 166
  • 288

2 Answers2

0

but the data present at index 1 are not shown

if (rs.next()) {
    while (rs.next()) {
        Object o[] = {rs.getString("username"), rs.getString("name"), ...
        tm.addRow(o);
    }

What do you think the rs.next() statement is doing?

The next() method points to the next row of data in the ResultSet.

You are skipping the first row because the if statement just point to the first row of data, but does nothing with it.

Get rid of the if statement, all you need is the while loop to access all the rows in the ResultSet.

camickr
  • 321,443
  • 19
  • 166
  • 288
  • ok, so how do I check table is empty or not. – Madhurmoms Jun 12 '22 at 06:48
  • 1
    If there are no rows in the ReultSet then your TableModel will be empty. You can always check the row count of your model after the looping code to see how many rows are in the model. – camickr Jun 12 '22 at 13:55
0

Better to do "no data" message check first and traverse through data otherwise. Something like this.

if(!resultSet.next()){
    JOptionPane.showMessageDialog(this, "No data found");
} 
else{
    do{
        Object o[] = {rs.getString("username"), rs.getString("name"), rs.getString("mobile"), rs.getString("email"), rs.getString("address"), rs.getString("date_time")};
        tm.addRow(o);
    }while (resultSet.next());
}
dds
  • 23
  • 5