仅查找全名,名字或姓氏

时间:2013-09-13 18:07:52

标签: java mysql

请帮助,我有一个小的java + mysql项目。它是一个人名的搜索程序。我有一个搜索框,您可以输入名称和“GO”按钮来执行。 我可以搜索:

santiago,martin <--- in this format. my problem is i cant search the following formats:

santiago  <-- input only lastname
 santiago <-- input with space before the lastname. 

这是我的代码。请赐教。我知道我的代码不好。或任何提高效率的建议。

String memberToFind = inSearchBar.getText();
    String[] memberToFindParts = memberToFind.split("\\,");
    String memberName0 = memberToFindParts[0];
    String memberName1 = memberToFindParts[1];
    int namelength = memberToFindParts.length;

    if(namelength!=0){
        String sql = "SELECT (accountNo) AS 'Account No',"
        + "(lastname)AS 'Lastname',"
        + "(firstname)AS 'Firstname'"
        + "FROM cmje.membertable "
        + "WHERE   ((accountno)LIKE '%"+memberName0+"%' OR "
                + " (accountno)LIKE '%"+memberName1+"%' OR "
                + " (lastname)LIKE '%"+memberName0+"%' OR "
                + " (lastname)LIKE '%"+memberName1+"%' OR "
                + " (firstname)LIKE '%"+memberName0+"%' OR "
                + " (firstname)LIKE '%"+memberName1+"%')"
                + " ORDER BY lastname DESC;";           

        try{
                pst = sqlconn.prepareStatement(sql);
                rs = pst.executeQuery();
                masterListTable.setModel(DbUtils.resultSetToTableModel(rs));
                    }catch(Exception e){
                        JOptionPane.showMessageDialog(null, e);
                    }
    }else if(namelength==0){
        String sql = "SELECT (accountNo) AS 'Account No',"
        + "(lastname)AS 'Lastname',"
        + "(firstname)AS 'Firstname'"
        + "FROM cmje.membertable "
        + "WHERE   ((accountno)LIKE '%"+memberToFind+"%' OR "
                + " (lastname)LIKE '%"+memberToFind+"%' OR "
                + " (firstname)LIKE '%"+memberToFind+"%')"
                + " ORDER BY lastname DESC;";


        try{
                pst = sqlconn.prepareStatement(sql);
                rs = pst.executeQuery();
                masterListTable.setModel(DbUtils.resultSetToTableModel(rs));
                    }catch(Exception e){
                        JOptionPane.showMessageDialog(null, e);
                    }
    }

2 个答案:

答案 0 :(得分:0)

您必须修剪输入字符串:

String memberToFind = inSearchBar.getText().trim();

答案 1 :(得分:0)

  

santiago&lt; - 在姓氏之前输入空格。

您可以轻松解决此问题:

String memberToFind = inSearchBar.getText().trim();
  

santiago&lt; - 仅输入姓氏

您应根据memberToFindParts的数量实施多种搜索模式。由于您无法知道用户的输入是名字还是姓氏,我认为您必须同时显示两个结果:

String[] memberToFindParts = memberToFind.split("\\,");
if(memberToFindParts.length == 2) {
    /*
     * search by fullname
     */
} else if(memberToFindParts == 1) { // Note currently you have namelenght==0 here and that's wrong
    /*
     * search by firstname and lastname separately
     */
} else {
    // input unexpected (0 or more than 2 words)
}