0

I have a method that returns an array list of search results from my database.

Instead of:

Select * 
from employee 
where first_name like ? 

I would rather use:

Select * 
from employee 
where ? like ? 

but I'm not sure if this is even possible? there's no errors when I compile it in eclipse but it keeps giving me blank values in the array. Is there something I'm doing wrong?

This is the method that gives me the blank value it works fine when I have where first_name like ? so I know the logic works.

public static ArrayList<String> AdvanceSearchFirstName(String selected, String searchTerm) {


    String selectQuery = "select * from employee_info where ? like ?";  

     ArrayList<String> searchResults = new ArrayList<>();
    try {
            stmt = con.createStatement();

    PreparedStatement ps = con.prepareStatement(selectQuery);
    ps.setString(1, selected);
    ps.setString(2, '%'+searchTerm+'%');
    ResultSet rs = ps.executeQuery();

    while (rs.next()) {

        String firstName = rs.getString("first_name");
        String lastName = rs.getString("last_name");
        String studentNumber = rs.getString("employee_number");

        String combo = employeeNumber + " " + firstName + " " + lastName;

                    searchResults.add(combo);
                 }

    } catch (SQLException e) {
        e.printStackTrace();
    }
    return searchResults;
}

I've looked over a lot of posts so I'm pretty sure this hasn't been posted but I apologies if this is a double. I'm new to programming and sql so any help is appreciated.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • 2
    The problem is that you're trying to use a placeholder for a column name, not a value. Although it's about a completely different language, and table names rather than columns, [this explanation of why this can't work](http://stackoverflow.com/a/15990488/157957) applies. The other answers to that question might give you some ideas on alternative solutions as well. – IMSoP Aug 06 '14 at 18:03
  • In this case, there's no error, because a value *could* go there, so that's what gets substituted in; you end up just comparing the two strings passed into the function, e.g. `where 'first_name' like '%bob%'`. `AdvanceSearchFirstName("test", "test")` would select all results. – IMSoP Aug 06 '14 at 18:06
  • I got it working thank you that link was very helpful. – user3428097 Aug 13 '14 at 12:05

0 Answers0