简体   繁体   中英

skip first row in resultset to JTABLE display

i want to display data in jtable when i use dbutil it skips the first row and show the other rows here is the code: i tried to make double loop with a rs.first() it didnt work

int id=0,quantite=0;
double prix=0.0;
ResultSet rs=null;
String sql = "Select id,prix,quantite from commande where quantite="+Integer.parseInt(tfRecherche.getText());
CommandeDao commande = new CommandeDao();
Statement st = commande.getSt();
try {
    rs= st.executeQuery(sql);
    while(rs.next()){
        if(rs.isFirst()){
            System.out.println("first");
        }
        id= rs.getInt("id");
        quantite = rs.getInt("quantite");
        prix = rs.getDouble("prix");
        tbAffichage.setModel(DbUtils.resultSetToTableModel(rs));
    }
} catch (SQLException ex) {
    Logger.getLogger(UI.class.getName()).log(Level.SEVERE, null, ex);
}

Get rid of the while loop as with it you are re-setting the JTable's table model each time it iterates, deleting any information added in the previous iterations. Instead it seems to make more sense to simply use the ResultSet and DbUtils.resultSetToTableModel to set the model once. Note that I've never used this utility, but it seems like it has to work this way. eg,

int id=0,quantite=0;
double prix=0.0;
ResultSet rs=null;
String sql = "Select id,prix,quantite from commande where quantite="+Integer.parseInt(tfRecherche.getText());
CommandeDao commande = new CommandeDao();
Statement st = commande.getSt();
try {
    rs= st.executeQuery(sql);

    // add this
    tbAffichage.setModel(DbUtils.resultSetToTableModel(rs));

    // and get rid of this...
    // while(rs.next()){
        // ....
    // }

} catch (SQLException ex) {
    Logger.getLogger(UI.class.getName()).log(Level.SEVERE, null, ex);
} finally {
    // close your connection here if not null, or use try-with resources
}

resultSetToTableModel(rs) consumes all rows in your resultset. The problem is, that you already consumed the first row with the rs.next() call.

That is, why the row is missing in the model.

Mine worked with the following code:

pst = conn.prepareStatement(sql);
res = pst.executeQuery();

if(res.isBeforeFirst())
{
    jTable1.setModel(DbUtils.resultSetToTableModel(res));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM