Query for searching the name alphabetically

前端 未结 5 1180
梦谈多话
梦谈多话 2020-12-12 06:04

I have used the LIKE condition, but it required me to enter the full name into the database to find the name.



        
相关标签:
5条回答
  • 2020-12-12 06:18

    Instead of

    StringBuilder sb = new StringBuilder();
    

    and

    sb.append(name + " ");
    

    do

    List names = new ArrayList<String>();
    

    and

    names.add(name);
    
    0 讨论(0)
  • 2020-12-12 06:18

    Instead of this:

    StringBuilder sb = new StringBuilder();
    while (rs.next()) {
    String name = rs.getString("Name");
    sb.append(name + " ");
    }
    

    Use this:

    List<String> lstNames = new ArrayList<String>();
    while (rs.next()) {
       lstNames.add(rs.getString("Name"));
    }
    
    0 讨论(0)
  • 2020-12-12 06:21

    WhiteFang34 also said you need to iterate. But also you need to change to WHERE clause:

    "SELECT * FROM FAMILYcensus WHERE Name > '"+ tfsearch.getText()+"' ORDER BY Name ASC LIMIT "+MAXRESULTS;
    

    Note that limiting the number of results is a good idea here.

    0 讨论(0)
  • 2020-12-12 06:28

    You need to iterate over the result set:

    while (rs.next()) {
        String name = rs.getString("Name");
        System.out.println("Name: " + name);
    }
    

    It looks like you had it and commented it out? If you want to store it in a list you had it right. If you want to put all of the results into a String for that tasearch.setText() you could:

    StringBuilder sb = new StringBuilder();
    while (rs.next()) {
        String name = rs.getString("Name");
        sb.append(name + " ");
    }
    String names = sb.toString().trim();
    tasearch.setText(names);
    
    0 讨论(0)
  • 2020-12-12 06:41

    I'm don't really understand your question clearly, but from what I understand, I'll post something that may help in solving your problem.

    Put your search string inside % as EmCo commented "'%"+ tfsearch.getText()+"%'"

    The % before and after the search string has different uses when you omit either one of this. See String Comparison Functions on how to use it.

    Now your another problem will be:

    You want the name in alphabetical order. For this you need to include ORDER BY. Then your query string will be.

    "SELECT 
            Name 
       FROM FAMILYcensus 
      WHERE Name LIKE '%" + tfsearch.getText() +"%' 
      ORDER BY Name ASC"
    

    Your search may result in more than one. Using just rs.next(); and String names = rs.getString("NAME"); will get only the first records I guess.

    You can try this code:

    List<String> names = new ArrayList<String>();
    while(rs.next){
        names.add(rs.getString('Name'));
    }
    

    The code I've provided is not tested. Though it will be like that or similar. Have a try if you still have a problem with your current code.

    0 讨论(0)
提交回复
热议问题