跳过结果集中的第一行到JTABLE显示

问题描述 投票:0回答:3

我想在jtable中显示数据,当我使用dbutil时它跳过第一行并显示其他行在这里是代码:我试图用rs.first()做双循环它没有工作

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);
}
java
3个回答
1
投票

摆脱while循环,就像每次迭代时重新设置JTable的表模型一样,删除前面迭代中添加的任何信息。相反,使用ResultSet和DbUtils.resultSetToTableModel设置模型一次似乎更有意义。请注意,我从未使用过此实用程序,但似乎必须以这种方式工作。例如。,

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
}

0
投票

resultSetToTableModel(rs)使用结果集中的所有行。问题是,您已经使用rs.next()调用消耗了第一行。

也就是说,为什么模型中缺少行。


0
投票

我使用以下代码:

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

if(res.isBeforeFirst())
{
    jTable1.setModel(DbUtils.resultSetToTableModel(res));
}
© www.soinside.com 2019 - 2024. All rights reserved.