请帮忙,我有一个小型 java + mysql 项目。它是一个搜索人名的程序。我有一个搜索框,您可以输入名称和“开始”按钮来执行。我可以搜索:
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);
}
}