Java Swing - 条件SQL查询

时间:2013-01-17 04:02:25

标签: java sql swing

我有一个sql select语句,通过从jComboBox&获取用户输入信息,通过jButton在我的jtable上显示查询。 jDateChooser。

是否可以为按钮设置条件,例如

以下代码为jButton action lisener

    java.util.Date dateFromDateChooser = jDateChooser.getDate();
    String dateString = String.format("%1$tY-%1$tm-%1$td", dateFromDateChooser);  

    String attendant = (String) cbName.getSelectedItem();
    String fill = "SELECT id as 'No', recDate as 'Date', super as 'Supervisor', attendant as 'Attendant' from log"
            + "WHERE recDate = '"+dateString+"'"
            + "and attendant = '" + attendant + "'";

    try{

        ps = conn.prepareStatement(fill);
        rs = ps.executeQuery();    
        jTable1.setModel(DbUtils.resultSetToTableModel(rs));

    }
    catch(Exception e){
        JOptionPane.showMessageDialog(null, e);
    }

} 上面的代码工作正常,但我希望允许用户使用两种类型的条件。 例如通过选择“Date and jComboBox”或“Date”

来显示搜索结果

我可以为这种情况使用if else语句吗?

请建议......

enter image description here

2 个答案:

答案 0 :(得分:1)

将检查添加到SQL大楼

String fill = "SELECT id as 'No', recDate as 'Date', super as 'Supervisor', attendant as 'Attendant' from log"
        + "WHERE recDate = '"+dateString+"'";

if(comboboxShouldBeIncluded) {
        fill+= " and attendant = '" + attendant + "'";
}

答案 1 :(得分:1)

如果未选择名称,则不带服务员进行查询

String attendant = (String) cbName.getSelectedItem();
    String qry;
    if( attendant != null && !attendant.isEmpty() ) {
     qry = "SELECT id as 'No', recDate as 'Date', super as 'Supervisor', attendant as 'Attendant' from log"
            + "WHERE recDate = '"+dateString+"'"
            + "and attendant = '" + attendant + "'";
    } else {
        qry = "SELECT id as 'No', recDate as 'Date', super as 'Supervisor', attendant as 'Attendant' from log"
            + "WHERE recDate = '"+dateString+"'";
    }