Jtable data retrieval problem in swing java

46 Views Asked by At

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

There are 2 best solutions below

2
camickr On

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.

0
dds On

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());
}