문제

I am trying to query a MS Access database from my java code and I am having no luck with the % wildcard that I read should work in other posts. The LIKE operator works if I exclude the wild cards from my code and provide the searchText variable with a value that matches exactly to a records Description. Below is the String queries I have tried that have either returned null or an exception:

String tableName = "SSPWO"; String desc = "[Description]";

  String query = String.format("SELECT * FROM %s WHERE " + desc + " LIKE '%" searchText +  "%' ORDER BY [WorkOrderNo] DESC", tableName);

|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||

String tableName = "SSPWO"; String desc = "[Description]";

  String query = String.format("SELECT * FROM %s WHERE " + desc + " LIKE '*" searchText +  "*' ORDER BY [WorkOrderNo] DESC", tableName);

|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||

String tableName = "SSPWO"; String desc = "[Description]";

  String query = String.format("SELECT * FROM %s WHERE " + desc + " LIKE \"%" searchText +  "%\" ORDER BY [WorkOrderNo] DESC", tableName);

|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||

String tableName = "SSPWO"; String desc = "[Description]";

  String query = String.format("SELECT * FROM %s WHERE " + desc + " LIKE \'%" searchText +  "%\' ORDER BY [WorkOrderNo] DESC", tableName);

Any help is greatly appreciated.

도움이 되었습니까?

해결책

The percent sign (%) is definitely the right wildcard character to use in this case. For test data

ID  Description                        
--  -----------------------------------
 1  I like apple pie.                  
 2  This is a test.                    
 3  Apple makes iThings.               
 4  This is another test.              
 5  Name of a tropical fruit: pineapple

the code

String tableName = "SSPWO"; 
String desc = "[Description]";
String searchText = "apple";
PreparedStatement ps = con.prepareStatement(
        String.format("SELECT * FROM %s WHERE %s LIKE ?", tableName, desc)
        );
ps.setString(1, "%" + searchText + "%");
ResultSet rs = ps.executeQuery();
while (rs.next()) {
    System.out.println(String.format("%d: %s", rs.getInt(1),rs.getString(2)));
}

produces the following console output

1: I like apple pie.
3: Apple makes iThings.
5: Name of a tropical fruit: pineapple

다른 팁

You've got a whack of syntax errors anyways:

String query = String.format([..snip...] + " LIKE '%" searchText 
                                                     ^---missing +
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top