Question

I'm making a little program, which has a connection with a database. Now i'm making a search option, you need to put your search criteria in a Textbox and after that hit the "search" button. I managed to do this successfully, only now I need to extend this. When there is no data found after you hit the "search" button a showMessageDialog needs to pop up with something like "there is no data found matching your search criteria".

How will I be able to do this? How can I integrate this into my existing code?

This is my search method so far:

private void zoekButtonActionPerformed(java.awt.event.ActionEvent evt) {                                           

    String naam = zoekField.getText();

    try {
        DefaultComboBoxModel dier = new DefaultComboBoxModel();

        Connection conn = SimpleDataSourceV2.getConnection();

        Statement stat = conn.createStatement();

        ResultSet rs = stat.executeQuery("SELECT * FROM dier WHERE rnaam = '" + naam + "';");

        ModelItem item;

        while (rs.next()) {
            item = new ModelItem();
            item.roepnaam = rs.getString("rnaam");
            item.geslacht = rs.getString("gesl");
            item.snr = rs.getInt("snr");
            dier.addElement(item);
        }
        rs.close();

        stat.close();

        lijst.setModel(dier);

    } catch (SQLException e) {
        JOptionPane.showMessageDialog(this, e.getMessage());
    }

}

Was it helpful?

Solution

I think a check for rs.isLast() or rs.isAfterLast() before your while look should help here. I'm not 100% sure which is the right one, but I think it should be rs.isAfterLast().

OTHER TIPS

private void zoekButtonActionPerformed(java.awt.event.ActionEvent evt) {

String naam = zoekField.getText();

try {
    DefaultComboBoxModel dier = new DefaultComboBoxModel();

    Connection conn = SimpleDataSourceV2.getConnection();

    Statement stat = conn.createStatement();

    ResultSet rs = stat.executeQuery("SELECT * FROM dier WHERE rnaam = '" + naam + "';");

    ModelItem item;

    if(rs.next()) {
        do{
           item = new ModelItem();
           item.roepnaam = rs.getString("rnaam");
           item.geslacht = rs.getString("gesl");
           item.snr = rs.getInt("snr");
           dier.addElement(item);
        }while(rs.next());
    }else{
        JOptionPane.showMessageDialog(this, "No data found");
    }
    rs.close();

    stat.close();

    lijst.setModel(dier);

} catch (SQLException e) {
    JOptionPane.showMessageDialog(this, e.getMessage());
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top