助けてください、私は小さな 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);
}
}