Home > other >  Jtable data retrieval problem in swing java
Jtable data retrieval problem in swing java

Time:06-12

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://img.codepudding.com/202206/54351c4ff5fb4b6e8ea8f647f545ab01.png

MySQL table img2:

https://img.codepudding.com/202206/a0d48a9536a44ea3aeff6582577396ee.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");
        }
    }

CodePudding user response:

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.

CodePudding user response:

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